java - 套接字在while循环中不发送数据
问题描述
我正在尝试进行简单的网络通信,其中客户端将用户输入字符串发送到服务器,然后服务器显示到控制台。当我只发送一个字符串时,它工作正常,但是一旦我包装我的用户输入代码并在 while 循环中发送代码,服务器就什么也没有收到。
服务器 :
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server now hosted on port " + PORT);
Socket s = serverSocket.accept();
System.out.println("A client has connected !");
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
while(true){
//RECEIVE
int data;
String inString = "";
while((data=bis.read()) != -1){
inString += (char)data;
}
System.out.println("SLAVE : " + inString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Port déjà utilisé");
}finally {
try {
serverSocket.close();
System.out.println("Server closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not close port " + PORT);
}
}
客户 :
Scanner sc = new Scanner(System.in);
Socket s = null;
try {
s = new Socket("127.0.0.1", PORT);
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
System.out.println("Connexion established !");
while(true){ // without this while loop, it works fine
String send = "";
System.out.print(">> ");
send = sc.nextLine();
bos.write(send.getBytes());
bos.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not connect");;
}
finally {
try {
s.close();
System.out.println("Closing socket");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not close connection");;
}
}
System.out.println("End of client");
}
我希望服务器在它即将到来时写入它从套接字读取的任何数据。但它什么也不做。我不确定问题是来自服务器还是客户端。
解决方案
问题出在您的while((data=bis.read()) != -1){
代码上。
它一直在循环,直到收到 EOS-1
当您没有客户端循环时,您的 Stream 将关闭,允许-1
发送,但当您有循环时则不会。尝试使用服务器循环打印,如下所示
while((data=bis.read()) != -1){
inString += (char)data;
if (((char)data) == '\n') {
System.out.println("SLAVE : " + inString);
inString = "";
}
}
推荐阅读
- javascript - Vue.js:延迟后运行方法,但如果用户输入发生则重置延迟
- c# - INotifyPropertyChanged 在可重置视图模型中不起作用
- r - 如何解决 R 中 ggplot 的多个错误栏问题?
- python - 遍历行并保存为 csv
- python - 在python中查询字典
- javascript - 如何使用 While 循环继续更改元素
- javascript - 如何在 HTML 中使用来自外部文件的 Jquery 对象?
- file - 需要帮助理解一个简短的批处理脚本(可能是骗局)
- javascript - 将 onClick 目标 URL 传递到 cookie
- matlab - 用 MATLAB 对两个不同的函数进行数值积分