简单的Java客户端和服务器无法正常交互

时间:2010-11-01 22:22:46

标签: java network-programming network-protocols

我无法理解为什么下面的代码不起作用。客户端向服务器发送消息,服务器将消息打印到标准输出。

服务器代码:

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);
        }
    }
}

任何见解?谢谢!

3 个答案:

答案 0 :(得分:3)

你应该做些什么来弄清楚这类问题,就是要找出问题所在。它是服务器部分还是客户端部分?对服务器的一个简单测试是启动它,然后telnet到该端口(例如“telnet 127.0.0.1 8080”)类型的东西,看看它是否正在输出。 (顺便说一下,你的服务器代码工作正常)。

这样做可以让您专注于您的客户端代码。正如Affe所说,你只是没有清除输入流。用于对代码进行故障排除的学习方法至少与学习编写代码一样重要。

另外,按照惯例,Java类以大写字母开头,因此它应该是“Server”和“Client”

答案 1 :(得分:1)

默认的PrintWriter不会自动刷新。 (并且不会因为抽象作家的表现而欺骗性地欺骗性地引导你相信。要么:

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

或者

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

答案 2 :(得分:0)

在您写入客户端中的流后添加刷新:


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

还要确保服务器套接字未被防火墙阻止