无法从java中的客户端 - 服务器程序中的客户端获取消息

时间:2014-10-05 01:10:03

标签: java

我正在使用TCP / IP在java中编写客户端 - 服务器程序。为此,我写了以下代码:

serversock.java:

import java.net.*;
import java.io.*;

public class serversock  {
     public static void main(String[] args) throws IOException
    {
        ServerSocket sersock = null;

        try 
        {
            sersock = new ServerSocket(10007);
        }

        catch (IOException e)
        {
            System.out.println("Can't listen to port 10007");
            System.exit(1);
        }

        Socket clientSocket = null;
        System.out.println("Waiting for connection....");


        try
        {
            clientSocket = sersock.accept();
        }

        catch ( IOException ie)
        {
            System.out.println("Accept failed..");
            System.exit(1);
        }

        System.out.println("Conncetion is established successfully..");
        System.out.println("Waiting for input from client...");

        PrintWriter output = new PrintWriter(clientSocket.getOutputStream());

        BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine = input.readLine();

        while ( inputLine  != null)
        {
            output.println(inputLine);
            System.out.println("Server: " + inputLine);
            inputLine = input.readLine();
        }
        input.close();
        clientSocket.close();
        sersock.close();

    }
}

clientsock.java:

import java.util.*;
import java.io.*;
import java.net.*;

public class clientsock 
{
    public static void main(String[] args) throws IOException
    {
        Socket sock = new Socket("localhost",10007);

        // Scanner scan = new Scanner(System.in);
        PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
        BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
        String line = null;

        BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));

        System.out.println("Enter data to send to server: ");
        line = stdInput.readLine();
        while ( (line) != "bye")
        {
            output.println(line.getBytes());
            line = stdInput.readLine();
            System.out.println("Server sends: " + input.read());
        }
        sock.close();

    }
}

现在运行程序我得到以下输出: 服务器:

shahjahan@shahjahan-AOD270:~/Documents/java$ java serversock 
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B@4e25154f
shahjahan@shahjahan-AOD270:~/Documents/java$ 

客户端:

shahjahan@shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server: 
qwe
sdf
^Cshahjahan@shahjahan-AOD270:~/Documents/java$

服务器正在接收不同的符号,客户端什么都没有收到。请帮我解决一下。

1 个答案:

答案 0 :(得分:0)

在客户端替换:

output.println(line.getBytes());

output.println(line);