我写了一个简单的Socket客户端程序,功能是把客户端接收到的数据再传回客户端,就像回音一样,可是执行到readUTF()就没有响应了,麻烦各位高手帮我看一下,下面是程序代码:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import java.io.*;public class SocketExample extends Applet
{
  private Socket sock;
  private DataInputStream dataIn;
  private DataOutputStream dataOut;  String srvName;
  int srvPort;
  Label label1,label2;
  TextField textfield_send,textfield_receive;
  Button button_send;
  
  public void init()
  {
   setLayout(new GridLayout(2,3));
  
label1 = new Label("请输入欲传送字串:");
label2 = new Label("Server 传回的字串:");
textfield_send = new TextField();
textfield_receive = new TextField();
textfield_receive.setEditable(false);

srvName = "localhost";
srvPort = 135;
makeConnection(); button_send = new Button("送出");
button_send.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
send_recive();
}
}); add(label1);
add(textfield_send);
add(button_send);
add(label2);
add(textfield_receive);  }  private void send_recive()
  {
try
{
dataOut.writeUTF(textfield_send.getText());
dataOut.flush();
System.out.println(textfield_send.getText());
textfield_receive.setText(dataIn.readUTF());//程序执行到这里就没有响应了
}
catch (IOException IOE)
{
System.err.println(IOE);
}
  }
  
  private void makeConnection()
  {
    try
    {
      InetAddress srvAddr=InetAddress.getByName(srvName);
      
      sock=new Socket(srvAddr,srvPort);
      dataIn=new DataInputStream(new BufferedInputStream(sock.getInputStream()));
      dataOut=new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
      System.err.println("Connection to server ok");
    }
    catch (IOException io)
    {
      System.err.println("Error:"+io);
    }
  }  public void stop()
  {
    try
    {
      dataOut.close();
      dataIn.close();
      sock.close();
    }
    catch (IOException io) {};
  }
}

解决方案 »

  1.   

    ReadUTF()是阻塞式的方法 ,效率不高 如果有客户端发送东西,服务器没接受, 其他客户端连不上去。
      

  2.   

    还有一个相似的例子,只要用到readUTF()时就没有响应,下面是程序代码:
    import java.io.*;
    import java.net.*;public class MainClass {
      public static void main(String[] args) throws Exception {
        String serverName = "localhost";
        int port = 135;    try {
          System.out.println("Connecting to " + serverName + " on port " + port);
          Socket client = new Socket(serverName, port);      System.out.println("Just connected to " + client.getRemoteSocketAddress());      OutputStream outToServer = client.getOutputStream();
          DataOutputStream out = new DataOutputStream(outToServer);
          out.writeUTF("Hello from " + client.getLocalSocketAddress());      InputStream inFromServer = client.getInputStream();
          DataInputStream in = new DataInputStream(inFromServer);
          System.out.println("Server says " + in.readUTF());//执行到这里就没有响应了      client.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }请各位高手帮我看看这是为什么,要如何解决,谢谢!