我有一个Server-Client
程序,我使用JLabel
向客户端发送一个小小的消息。当从服务器收到该消息时,特定客户端必须立即发送响应。但它没有发送任何消息。有人可以看看我的代码并告诉我我的错误在哪里吗?
// SERVER
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);
}
}
// CLIENT
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);
}
}
答案 0 :(得分:1)
您在实施中遗漏的一些要点:
举一个简单的例子,步骤应该是:
示例:
//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
}