1

我正在创建一个需要在网络上的多台计算机之间来回传输数据的应用程序。由于要发送数据的方式,客户端计算机将运行套接字服务器,而协调计算机将运行客户端套接字。

我创建了简单的类,它们只是为了封装对这些套接字的读取和写入。然而,接收套接字并没有读取任何内容,而是什么都不输出。我已经确认客户端和服务器都有连接。

在以下ServerClient类中,Socket公开仅用于调试目的。

public class Server {
    public Socket client;
    private DataInputStream inStr;
    private PrintStream outStr;

    public Server() throws UnknownHostException, IOException {this("localhost");}
    public Server(String hostname) throws UnknownHostException, IOException {
        client = new Socket(hostname, 23);
        inStr = new DataInputStream(client.getInputStream());
        outStr = new PrintStream(client.getOutputStream());
    }

    public void send(String data) {outStr.print(data); outStr.flush();}
    public String recv() throws IOException {return inStr.readUTF();}
}

以下是我的Client

public class Client {
    private ServerSocket serv;
    public Socket servSock;
    private DataInputStream inStr;
    private PrintStream outStr;

    public Client() throws IOException {
         serv = new ServerSocket(23);
         servSock = serv.accept();
         inStr = new DataInputStream(servSock.getInputStream());
         outStr = new PrintStream(servSock.getOutputStream());
    }

    public void send(String data) {outStr.print(data); outStr.flush();} 
    public String recv() throws IOException {return inStr.readUTF();}
}

Client 类被实例化,程序启动。然后,在一个单独的程序中,服务器被实例化并启动:

Server s = new Server(); System.out.println(s.client.isConnected());  
while(true) {System.out.println(s.recv()); Thread.sleep(200);}

Client c = new Client(); System.out.println(c.servSock.isConnected()); 
while(true) {c.send("Hello World!"); Thread.sleep(200);}

isConnected()返回true

这可能是什么原因造成的?我以前从未使用过套接字。

4

1 回答 1

2

DataInputStream.readUTF() expects the first two bytes to be the number of bytes to read, but PrintStream.print(String) will convert the string to bytes and write them as-is.

DataOutputStream.writeUTF(String) will write the length like readUTF() expects.

于 2013-04-17T04:36:07.503 回答