Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Eck, D. J. (2019) says, a Socket represents one endpoint of an actual network connection.

A
Socket can be a client socket that sends a connection request to a server. created by a server
to handle a connection request from a client. So a Socket can be used for a client and a server.

Eck, D. J. (2019) says, a ServerSocket listens for connection requests creates Sockets to handle
the actual connections. So a ServerSocket itself does not connect with a client.

When you construct a ServerSocket, listen for a connection request, and establish a
connection with a client, you can write as follows:

// You should specify the port number.

ServerSocket server = new ServerSocket(1234);

// continue listening

while (true){

Socket connection = server.accept();

someProcess(connection);

You should wrap the above code with try ... catch.

When you construct a Socket, you can write as follows:

// You have to specify the computer and the port

Socket connection = new Socket( computerName, serverPort);

in = connection.getInputStream();

out = connection.getOutputStream();

You should also wrap the above code with try ... catch

When you construct a ServerSocket, you should specify the Port. When you specify a Socket,
you should specify the IP number or a domain name of the server and the port number of it.
Sockets have getInputStream method and getOutputStream method. You can communicate
with the server by these methods.

It is better to wrap the constructors of a ServerSocket and Socket in try..catch.

Reference:

Eck, D. J. (2019). Introduction to programming using Java, version 8.1. Hobart and William
Smith Colleges

You might also like