0

我有 2 个程序:一个客户端和一个服务器。

服务器创建一个 ServerSocket,客户端使用以下命令进行连接:

address = InetAddress.getByName(host);
conn = new Socket(address, port);

这可行,但问题void mousePressed() {是:单击鼠标后调用,执行此操作:(客户端)

void mousePressed() {
  try {
    BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
    OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
    osw.write("123");
        osw.flush();
      } catch (Exception e) {
        e.printStackTrace();
      }
}

服务器应该使用以下命令接收输入:

BufferedReader reader = new BufferedReader(
new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
StringBuilder result = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
    result.append(line);
}
reader.close();
println(result.toString());

服务器仅在套接字关闭后接收输入:conn.close();在客户端或退出客户端。因为我希望能够多次单击鼠标,所以我无法关闭套接字。

我该怎么做才能在不关闭套接字的情况下发送输入?

编辑:连接代码:

服务器:

 // init
    ServerSocket socket1;
    int main_port = 5204;
    // in main
    try {
          socket1 = new ServerSocket(main_port);
          Socket conn = socket1.accept();
        } catch (Exception e) {
            e.printStackTrace();
        }

客户:

// init
    String host = "localhost";
    int port = 5204;
    Socket conn;
    InetAddress address;
    // in main
    try {
          address = InetAddress.getByName(host);
          conn = new Socket(address, port);
         } catch (Exception e) {
                e.printStackTrace();
            }
4

2 回答 2

1

我的解决方案(基于其他答案和评论):

1)在客户端更改osw.write("123");osw.write("123\n");

2) 更换

    BufferedReader reader = new BufferedReader(new InputStreamReader(new
BufferedInputStream(thread_cnn.getInputStream())));        
        StringBuilder result = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
    result.append(line);
}
println(result);
reader.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));        
String result = reader.readLine().toString();
println(result);
reader = null;
result = null;

在服务器上。

于 2013-10-06T09:48:02.290 回答
0

你正在写一个不完整的行,并试图阅读完整的行。用换行符终止您发送的文本,以便在它到达时可以阅读。

此外,不要捕获和忽略异常。如果出现问题,您将想知道它。

  try {
    BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
    OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
    osw.write("123\n");
    osw.flush();
  } catch (Exception e) {
    e.printStackTrace();
  }
于 2013-10-06T09:27:37.620 回答