我正在实施一个简单的聊天应用程序。 服务器必须侦听多个客户端,并且服务器必须将一个客户端输入的数据发送到连接到此服务器的所有客户端。 我已通过以下代码实现了这一点。出乎意料的是我得到 java.net.SocketException:socket closed 。 任何人都可以解决此异常,并告诉我必须修改代码以将数据发送到所有客户端。
Client.java
import java.io.*;
import java.net.*;
import java.util.*;
class Client {
public static void main(String args[]) {
try {
InetAddress addr = InetAddress.getByName("172.26.45.132");
Socket skt = new Socket(addr, 1234);
PrintWriter out = new PrintWriter(skt.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
Scanner sc = new Scanner(System.in);
String msg="";
while (msg!="exit") {
msg= sc.next();
out.println(msg);
System.out.println("from Server"+br.readLine());
}
br.close();
out.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Server.java
import java.io.*;
import java.net.*;
class Server {
public static ListenClient clients[] = new ListenClient[3];
public static int clientCount = 0;
public static void main(String args[]) {
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt;
System.out.print("Server has connected!\n");
while(clientCount < 3){
skt = srvr.accept();
clients[clientCount] = new ListenClient(skt,clientCount);
Thread t = new Thread(clients[clientCount]);
clientCount++;
t.start();
}
}
catch(Exception e) {
System.out.println(e);
System.out.print("Whoops! It didn't work!\n");
}
}
}
class ListenClient extends Server implements Runnable{
Socket sc;
int id;
ListenClient(Socket sc, int id){
this.sc=sc;
this.id = id;
}
public void run(){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
String msg="";
while((msg=br.readLine())!=null)
{
PrintWriter clientsOut;
for(int j = 0 ; j<=clientCount-1; j++){
clientsOut = new PrintWriter(clients[j].sc.getOutputStream(),true);
clientsOut.println(msg);
clientsOut.close();
}
}
}
catch(Exception e){
System.out.println(e);
}
}
}
答案 0 :(得分:1)
SocketClosedException意味着你关闭了套接字,然后继续使用它。关闭输入或输出流将关闭套接字和另一个流。因此,在读取输入的循环内关闭输出是没有意义的。