2010-11-01 81 views
0

我不明白为什么下面的代码不起作用。客户端向服务器发送消息,服务器将消息打印到标准输出。简单的Java客户端和服务器没有正确交互

代码服务器:

import java.net.*; 
import java.io.*; 
import java.math.BigInteger; 

public class server 
{ 
    public static void main(String args[]) 
    { 
     try 
     { 
      ServerSocket server = new ServerSocket(8080); 

      while (true) 
      { 
       // initializations 
       Socket connection = server.accept(); 
       BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
       PrintWriter out = new PrintWriter(connection.getOutputStream()); 

       // listen for client message 
       String message = in.readLine(); 

       // print raw message from client 
       System.out.println(message); 

       // close resources 
       if (out != null) 
        out.close(); 
       if (in != null) 
        in.close(); 
       if (connection != null) 
        connection.close(); 
      } 
     } 
     catch (Exception e) 
     { 
      System.out.println(e.getMessage()); 
      System.exit(1); 
     } 
    } 
} 

代码客户端:

import java.net.*; 
import java.io.*; 
import java.math.BigInteger; 

public class client 
{ 
    public static void main(String args[]) 
    { 
     try 
     { 
      // initializations 
      Socket connection = new Socket("localhost", 8080); 
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
      PrintWriter out = new PrintWriter(connection.getOutputStream()); 

      // send message to server 
      out.println("Hello, world!"); 

      // close resources 
      if (in != null) 
       in.close(); 
      if (out != null) 
       out.close(); 
      if (connection != null) 
       connection.close(); 
     } 
     catch (Exception e) 
     { 
      System.out.println(e.getMessage()); 
      System.exit(1); 
     } 
    } 
} 

任何见解?谢谢!

+0

它错误说什么? – Jorge 2010-11-01 22:24:00

+0

没有“错误”;代码编译得很好。但是在启动服务器和客户端之后,服务器挂起而不打印任何内容到标准输出。 – 2010-11-01 22:25:29

+0

挂在哪里?在调试器下运行或添加一些printlns来找出哪里?客户端是否运行并终止,没有任何错误? – 2010-11-01 22:27:39

回答

1

默认的PrintWriter不自动刷新。 (和亘古不变的接近抽象的作家冲洗看似可能会导致你相信无论做:

PrintWriter out = new PrintWriter(connection.getOutputStream(), true); 

否则

out.println("Hello, world!"); 
    out.flush(); 
3

,你应该做的事情弄清楚这种类型的问题,是隔离出问题的地方,它是服务器部分还是客户端部分?一个简单的服务器测试就是启动服务器,然后telnet到该端口(例如“telnet 127.0.0.1 8080”)键入某个内容看看它是否正在输出(顺便说一句,你的服务器代码工作正常)

这样做会允许你要专注于你的客户端代码。正如情绪所述,你只是没有清除输入流。学习代码故障的学习方法至少与学习编写代码一样重要。

同样作为不谈,按照惯例,Java类以大写字母开头,所以它应该是“服务器”和“客户”

+0

感谢您的建议。不幸的是,对于作业而言,规范要求使用小写字母的名字。 – 2010-11-01 23:30:35

0

添加冲洗你写在你的客户流后:

 

      // send message to server 
      out.println("Hello, world!"); 
      out.flush(); 
 

而且确保服务器套接字没有通过防火墙阻止