我有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());
服务器仅在客户端上使用以下命令关闭套接字或退出客户端后才接收输入。由于我希望能够多次单击鼠标,因此无法关闭插座。
如何在不关闭套接字的情况下发送输入?
编辑:连接代码:
服务器:
// 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();
}
最佳答案
我的解决方案(基于其他答案和评论):
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;
在服务器上。