我有 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();
}