Java SwingWorker和TCP连接工作不正常
我有以下代码,描述了如果窗口打开,它将显示一个对话框,连接到服务器并接收数据:Java SwingWorker和TCP连接工作不正常,java,swing,tcp,Java,Swing,Tcp,我有以下代码,描述了如果窗口打开,它将显示一个对话框,连接到服务器并接收数据: private void formWindowOpened(java.awt.event.WindowEvent evt) { this.jDialog1.setVisible(true); con = new Conexion(); SwingWorker work = new SwingWorker() {
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
,这意味着客户端实际上已连接到服务器,但由于某种原因,它没有从服务器读取数据 为了实现这一点,我所做的只是将通常的DataInputStream
和DataOutputStream
替换为ObjectInputStream
和ObjectOutputStream
。问题解决了,它成功了。您可以将您的代码与这个完整的、有效的代码进行比较。引起我注意的是使用了扫描仪和PrintWriter
,而不是DataInputStream
和DataOutputStream
。为什么我要选择一个而不是另一个呢?哦,还有,我刚刚用Scanner
和PrintWriter
进行了测试,在尝试读取字符串时得到了相同的结果。由于某些原因,客户端没有从服务器接收任何数据!!请看这个。谢谢!!这给了我一个想法,我要张贴,它的工作!!