我正在实现一个简单的聊天应用程序。服务器必须监听多个客户端,并且服务器必须将一个客户端输入的数据发送给连接到该服务器的所有客户端。我已经通过以下代码实现了这一点。出乎意料的是,我得到了java.net.SocketException: socket closed。任何人都可以解决此异常并告诉我必须在哪里修改代码以将数据发送给所有客户端。
客户端.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");
}
}
}
服务器.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);
}
}
}