0
我的客户机 - 服务器应用程序有点问题。当我想要连接超过1级的客户端和发送不便,或者我做注销我的客户端,并尝试一次我得到异常连接: “java.io.StreamCorruptedException:无效类型代码:04”java.io.StreamCorruptedException:无效的类型代码:04
什么问题?感谢帮助。
服务器代码:
class ClientCommunication implements Runnable {
private Socket incoming;
public ClientCommunication(Socket clientSocket) {
incoming = clientSocket;
}
public void run() {
try {
synchronized (this) {
serverObjectOutput = new ObjectOutputStream(
incoming.getOutputStream());
serverObjectInput = new ObjectInputStream(
incoming.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
int operation = -1;
synchronized(this) {
while (true) {
try{
if(serverObjectInput.available() > 0){
operation = serverObjectInput.readInt();
switch(operation) {
case 1:
Employee employee = (Employee) serverObjectInput.readObject();
//CHECK LOGGING DATA
// SEND RESULT = 1 OR RESULT = -1
break;
}
}
} catch(IOException | ClassNotFoundException | SQLException ex)
{
ex.printStackTrace();
}
}
}
}
}
class ServerStart implements Runnable {
private int portNumber;
public ServerStart(int portNumber) {
this.portNumber = portNumber;
}
public void run() {
try {
conn = getConnection();
stat = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
Socket incoming = serverSocket.accept();
Runnable r = new ClientCommunication(incoming);
Thread t = new Thread(r);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
客户端功能:
public void actionPerformed(ActionEvent e) {
if (isConnected == false) {
String ServerIP = ip.getText().trim();
int ServerPort = Integer
.parseInt(port.getText().trim());
try {
ClientSocket = new Socket(ServerIP, ServerPort);
clientObjectInput = new ObjectInputStream(
ClientSocket.getInputStream());
clientObjectOutput = new ObjectOutputStream(
ClientSocket.getOutputStream());
isConnected = true;
} catch (IOException ex) {
ex.printStackTrace();
}
synchronized (this) {
try {
ClientLoginFrame login = new ClientLoginFrame();
Employee employee = login.getEmployee();
clientObjectOutput.writeInt(1);
clientObjectOutput.flush();
clientObjectOutput.writeObject(employee);
int result = clientObjectInput.readInt();
if(result == 1)
{
// DO SMTH
}
else {
isConnected = false;
ClientSocket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
为什么当你可以使用阻塞阅读哪一个会简单得多。在写对象之前flush也不会做任何事情,写对象之后flush和可能的'reset()'可能会更有用。 – 2014-12-27 13:48:22
当你遇到异常时,我不会假装它没有发生,只是继续。你需要在整个事情中加入try/catch,并关闭连接。 – 2014-12-27 13:50:35
我建议分离GUI和网络处理类,并单独测试网络类。 – 2014-12-27 13:51:23