我正在尝试使用套接字在java中创建一个小服务器。 套接字已连接,但是当我从客户端向我的服务器发送数据时,它会出现异常。
stacktrace(更新):
IOException on socket listen: java.net.SocketException: Connection reset
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at org.codox.game.network.NetworkController$doComms.run(NetworkController.java:81)
at java.lang.Thread.run(Unknown Source)
如果您需要更多信息,请告诉我
欢迎任何建议
THX
- 已编辑 -
完整的服务器代码:
class doComms implements Runnable
{
private Socket server;
PackageHandler packageHandler;
doComms(Socket server)
{
this.server = server;
packageHandler = new PackageHandler();
}
public void run()
{
try
{
ObjectInputStream ois = new ObjectInputStream(server.getInputStream());
ClientPackage clientPack = (ClientPackage) ois.readObject();
RespondPackage rp = packageHandler.handlePackage(clientPack);
ObjectOutputStream ous = new ObjectOutputStream(server.getOutputStream());
ous.writeObject(rp);
ous.flush();
server.close();
System.out.println("Connection was finished and closed.");
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ioe)
{
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
完整的客户端代码:
SocketHints hints = new SocketHints();
hints.keepAlive = true;
hints.connectTimeout = 2000;
Socket socket;
try
{
socket = Gdx.net.newClientSocket(Protocol.TCP, "127.0.0.1", 12346, hints);
ClientPackage client = new ClientPackage();
client.setRequestType(RequestType.ping);
ObjectOutputStream ous = new ObjectOutputStream(socket.getOutputStream());
ous.writeObject(client);
ous.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
RespondPackage response = (RespondPackage) ois.readObject();
System.out.println("Respone type = " + response.getRequestType());
} catch (UnknownHostException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e)
{
}