我正在使用套接字创建一个swt服务器。问题是我的服务器端代码在调用accept()
方法后没有执行。奇怪的是,相同的代码在普通的java应用程序中完美地执行,而不使用swt。也许,我实施的swt线程可能有问题。
以下是代码段。
new Thread(new Runnable() {
@Override
public void run() {
try {
serverSocket = new ServerSocket(4439);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
System.out.println("before");
socket = serverSocket.accept();
System.out.println("after");
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Display.getDefault().syncExec(new Runnable() {
public void run() {
text.append("Listening:\n");
text.append("ip: " + socket.getInetAddress());
try {
text.append("message: " + dataInputStream.readUTF());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}).start();