1

我的 TCP 服务器是这样的。

import java.net.*;
import java.io.*;
public class NetTCPServer {
public static void main(String[] args) throws Exception{

ServerSocket sock;
sock = new ServerSocket(1122);
if(sock == null)
    System.out.println("Server binding failed.");
System.out.println("Server is Ready ..");

do{
    System.out.println("Waiting for Next client.");
    Socket clientSocket = sock.accept();
    if(clientSocket!=null)
        System.out.println("Clinet accepted. "+sock.getInetAddress().getHostAddress());

    DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
    //DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String name;
    String pass;
    String line;
    name = in.readLine();
    pass = in.readLine();
    for(int i=0;i<name.length();i++)
        System.out.print(name.charAt(i)+","); //see more null char are receiving here

        System.out.println("");
        System.out.println(name +"  "+ name.length()+"  \n" + pass+"  "+pass.length());
    }while(true);

}
}

并且各自的TCP Client如下。

import java.net.*;
import java.io.*;
public class NetTCPClient {

    public static void main(String[] args) throws Exception {
        InetAddress addr = InetAddress.getByName("localhost");

        Socket sock;
        sock = new Socket(addr,1122);
        if(sock == null)
            System.out.println("Server Connection failed.");
        System.out.println("Waiting for some data...");
        DataInputStream input = new DataInputStream(sock.getInputStream());
        DataOutputStream output = new DataOutputStream(sock.getOutputStream());
        String uname="ram";
        String pass="pass";
        output.writeChars(uname+"\n");// \n is appended just make to readline of server get line
        output.writeChars(pass+"\n");
        }

}

当我编译两者并启动服务器并在客户端运行后在那里运行时,我得到以下输出。

Server is Ready ..
Waiting for Next client.
Clinet accepted. 0.0.0.0
,r,,a,,m,,
ram7  pass9

每个字符接收后的空字符对我来说有点奇怪。使我无法将字符串与存储在服务器中的内容进行比较。这些空字符是什么,它们来自哪里。

4

1 回答 1

0

您写入字符但读取字节。那是行不通的。如果要写入字符,则需要以完全相同的编码读取字符。如果要写入字节,则需要读取字节。在字节级别精确地指定您的协议,并遵循客户端和服务器中的规范。

有关更多信息,请参阅此问题

于 2013-09-19T06:41:26.553 回答