0
我有下面的代碼,它描述瞭如果打開一個窗口,它應該呈現一個對話框中可見,連接到服務器,並接收數據:的Java SwingWorker類和TCP連接不能正常工作
private void formWindowOpened(java.awt.event.WindowEvent evt) {
this.jDialog1.setVisible(true);
con = new Conexion();
SwingWorker work = new SwingWorker() {
@Override
public Object doInBackground() {
con.recibirDatos();
return null;
}
@Override
public void done() {
jDialog1.dispose();
jDialog2.setVisible(true);
}
};
work.execute();
}
現在, Conexion
執行以下操作,客戶明智的:
public Conexion() {
try
{
this.puerto = 7896;
this.s = new Socket("localhost", puerto);
this.entrada = new DataInputStream(s.getInputStream());
this.salida = new DataOutputStream(s.getOutputStream());
}
catch(UnknownHostException e){ System.out.println("Socket: "+e.getMessage()); }
catch(EOFException e){ System.out.println("EOF: "+e.getMessage()); }
catch(IOException e){ System.out.println("IO: "+e.getMessage()); }
}
public void recibirDatos() {
try
{
this.salida.writeUTF("sendData");
System.out.println("Leyendo...");
this.color = this.entrada.readUTF();
this.ancho = this.entrada.readInt();
System.out.println("Datos recibidos: "+color+" "+ancho);
}
catch(UnknownHostException e){ System.out.println("Socket: "+e.getMessage()); }
catch(EOFException e){ System.out.println("EOF: "+e.getMessage()); }
catch(IOException e){ System.out.println("IO: "+e.getMessage()); }
}
服務器的角度來看,將出現以下情況時,連接讀:
public void enviarDatos(String color, int anchoLinea) {
try
{
System.out.println(entradaCliente.readUTF()+"! Enviando datos: "+color+" "+anchoLinea);
salidaCliente.flush();
salidaCliente.writeUTF(color);
salidaCliente.writeInt(anchoLinea);
System.out.println("Datos enviados.");
}
catch(EOFException e){ System.out.println("EOF: "+e.getMessage()); }
catch(IOException e){ System.out.println("IO: "+e.getMessage()); }
}
問題:
- 當我執行此,客戶卡上
readUTF()
雖然 服務器已經發送的數據。 - 如果我只發送和接收整數,我得到價值
-1393754107
,而不是我發送的號碼,但客戶端不會卡住。 - 當我從客戶端發送數據到服務器,它工作得很好。
可能是什麼問題?事先謝謝你。
編輯:我還發現,如果服務器關閉而客戶端在等待由於readUTF()
,客戶得到的IOException
,這意味着客戶實際上是連接到服務器,但由於某種原因它不讀來自它的數據!
您可以將您的代碼與此完整的工作[示例]進行比較(http://stackoverflow.com/a/3245805/230513)。 – trashgod
引起我注意的是'Scanner'和'PrintWriter'的使用,而不是'DataInputStream'和'DataOutputStream'。爲什麼我應該選擇一個呢? –
哦,而且,我剛剛使用'Scanner'和'PrintWriter'進行了測試,並且在嘗試讀取字符串時得到了相同的結果。出於某種原因,客戶端沒有收到來自服務器的任何數據! –