短いストーリー、このコードは完璧に動作しています。私はできるだけ少なくしたいと思っています。これは多才なserversocketです、私のためにはうまくいっています。私が変更したいのは、singleClientに変更することだけです。Java、マルチクライアントServertSocketをシングルに変換
クライアント#1は接続され、サーバーと通信しますが、クライアント#2は接続しようとしますが、クライアント#1はまだ接続されているため、接続できません。サーバーに接続して話をする。
今、私のコードは、すべてのクライアントが同時に接続して話すことができるという点を除いて、まったく同じことをしています。これは私が望まないものです。 P.s - クライアント側は正常に動作しています。ただ、サーバーサイドで助け、そして最後に一つ必要、私はJavaSavvyないんだけど、そうspoonfeedingが大幅に高く評価されています。これを行うには$
Socket s=null;
ServerSocket ss2=null;
Status = ("Server Listening......");
try{
ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
ServerThread serverThread = null;
while(true){
try{
s= ss2.accept();
Status = ("connection Established");
if (serverThread == null || !serverThread.isAlive()) {
ServerThread st=new ServerThread(s);
st.start();
}
else
s.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
class ServerThread extends Thread{
String str = "Hello";
String line=null;
BufferedReader is = null;
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println("Hi");
line=br.readLine();
String input = br.readLine().replaceAll("[^A-Za-z0-9]", "");
while ((input = br.readLine()) != null) { //Here is the loop part
input = input.replaceAll("[^A-Za-z0-9]", "");
if(input.contains("Done")){
System.out.println("We closing it");
s.close();
}
else if (input.equals(str)) {
System.out.println("We received : " + str);
pw.println("Hi");
}
if (input.contains(str)){
Finite();
}
if(input.contains("Done")){
System.out.println("We closing it");
s.close();
}
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if (is!=null){
is.close();
System.out.println(" Socket Input Stream Closed");
}
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
}
を必要としません。サーバーに、あなたが推薦した変更の後に完全なコードを更新しました、まだ運がありません。 – BioPipeRex
それは私のために働いています:2番目のクライアントが接続すると、サーバーはソケットを閉じます。何を見ていますか? 「サーバーと話す」とはどういう意味ですか? – ck1
あなたのお勧め後に私のアップデートをチェックしましたか? DId私はそれを正しく行う?私が見ていることは、サーバーとすべてのクライアントが同時に話していることです。 (あなたの最後の質問に関しては、このプロジェクトは基本的に "Hello"と "Hi"によってクライアントと話す1台のサーバです。 – BioPipeRex