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