gpt4 book ai didi

java - 消息未从客户端发送到服务器 - Java

转载 作者:行者123 更新时间:2023-11-30 08:14:56 27 4
gpt4 key购买 nike

我有一个服务器-客户端程序,我使用JLabel向客户端发送一条小消息。当从服务器收到该消息时,特定客户端必须立即发送响应。但它没有发送任何消息。有人可以看看我的代码并告诉我错误在哪里吗?

//服务器

void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
while (true) {

socket = listener.accept();
socketList.add(socket);
//socketList.add(listener.accept());
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);

}

}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
}

//客户端

 void connect_server() throws IOException
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);

while(true){
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
if(answer != null)
{
PrintStream pr = new PrintStream(s.getOutputStream());
InputStreamReader rd = new InputStreamReader(System.in);
BufferedReader ed = new BufferedReader(rd);
String temp = ed.readLine();
pr.println(temp);

JOptionPane.showMessageDialog(null,"Answer is not null"); //THIS WORKS
}

}

}
catch (ConnectException e) {

JOptionPane.showMessageDialog(null, e);
}
catch (SocketException e) {

JOptionPane.showMessageDialog(null, e);
}
}

最佳答案

您在实现过程中遗漏的一些要点:

  • 流和套接字永远不会关闭
  • 在客户端我看不到无限循环的意义
  • 客户端应通过输出流发送消息来初始化通信(不要尝试先读取)

举一个简单的例子,步骤应该是:

  1. 启动服务器进行监听,一旦建立连接即可读取消息(您已完成)
  2. 客户端应通过输出流发送消息并关闭流和套接字
  3. 服务器应关闭已建立连接的流和套接字

示例:

//Server
socket = listener.accept();
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream());
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
String msg = "Message received";
pr.write(msg,0,msg.length());
pr.newLine();
ed.close();
pr.close();
socket.close();

//Client
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(s.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sendMessage = "Send Message";
pr.write(msg,0,msg.length());
pr.newLine();
String answer = input.readLine();
System.out.println(answer);
JOptionPane.showMessageDialog(null,"Answer is not null");
input.close();
pr.close();
s.close();

更新

连续从输入流读取:

BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line=input.readLine())!=null){
//do something with line
}

关于java - 消息未从客户端发送到服务器 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com