views:

69

answers:

2

I have this code:

ServerSocket serverSideSocket = new ServerSocket(1234);
        serverSideSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));

And compiler writes me that it cannot find "getInputStream". I do not understand why. In the beginning of my code I do import java.net.*.

+8  A: 

Calling of accept returns instance of Socket which has required method getInputStream.

The code might look like this:

ServerSocket serverSideSocket = new ServerSocket(1234);
Socket socket = serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Great tutorial how to work with sockets in java: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

uthark
A: 

This because conceptually a ServerSocket doesn't provide a direct connection object that can be used to send and receive data. A ServerSocket is a tool that you can use with the .accept() method to let it listen on the choosen port and generate a new real connection when a client tries to connect.

That's why you can't get an InputStream from a ServerSocket. Since many clients can connect to the same server, every client will make the server socket generate a new Socket (that is an opened TCP connection) that is returned from .accept() through which you can send and receive using its InputStream and OutputStream.

Jack