我正在尝试制作一个使用tcp连接的客户机/服务器程序,并使用本地主机IP和端口12345在同一台计算机(服务器和客户端)上测试它。
我使用ObjectInputStream和ObjectOutputStream来接收和发送消息。有时 my程序工作perfect,它按照我的意愿发送正确的消息,但有时(在程序的随机时间/阶段),我的客户端之一“失去”连接,他进入无限循环,打印"null"或无效类型代码:54“< code >E29而不做任何代码更改。
我没有错误,只有服务器打印“连接重置”循环中的和客户机"null"或无效类型代码:54“catch (IOException e)中的”。
我将向您展示我的代码的基本知识。
服务器:
代码语言:javascript运行复制 public static void main(String[] args) {
//--------BASIC CODE used for connection stuff below----//
server = new ServerSocket(12345);
connection =server.accept();
Thread thread =new Thread(new ClientThread(connection,GRM...));
thread.start();
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
}
--------------//---------thread for each client----------//--------------
do{
try{
message=(String) input.readObject();
if(message.startsWith("SOMENTHING"))//...some tcode
if(message.equals("SEND")){
String message="hi";
output.writeObject("Chat:"+message);output.flush();
UserW.writeObject(message);UserW.flush();
//UserW is an output from another client stored in the server
}
catch(ClassNotFoundException classNotFoundException){
System.out.print("\nUnknown object");
}catch (IOException e) {
System.out.println(e.getMessage());
}
}while(!message.equals("DISCONNECT"));客户端:
代码语言:javascript运行复制 public static void main(String[] args) {
connection=new Socket(InetAddress.getByName("127.0.0.1"),12345);
//...... same logic with streams......//
}
//-------thread that receives from server-----//
do{
try{
String message=(String) input.readObject();
//.....some code....//
}catch( ClassNotFoundException classNotFoundException){
System.out.print("\nUnknown object");
}catch (IOException e) {
System.out.println(e.getMessage());
}
}while(true);