user1131435
user1131435

Reputation:

Reading and writing from a socket produces no output?

I'm creating an application which will need to transmit data back and forth between multiple computers on a network. Because of the way the data is to be sent, the client computers will be running the socket server, and the coordinating computer will be running the client socket.

I've created simple classes which are simply intended to encapsulate reading from and writing to these sockets. However, instead of reading anything, the receiving socket simply outputs nothing. I have confirmed that both client and server have a connection.

In the following Server and Client classes, the Socket is made public for debugging purposes only.

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

The following is my 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();}
}

The Client class is instantiated, and the program started. Then, in a separate program, the Server is instantiated and started:

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() returns true for both the Client and the Server.

What could be causing this? I've never had to use sockets before now.

Upvotes: 1

Views: 599

Answers (1)

tom
tom

Reputation: 22939

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.

Upvotes: 2

Related Questions