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 クライアントは以下のとおりです。

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 に答える