Almighty Bus Error

Loading search...

The connection-oriented network protocol

The TCP and unlike UDP it does have a connection definition within the protocol based on Acknowledge-type packets.

In TCP every sent information packet needs to be acknowledged by the destination and if it is missing, the packet is resent until there is confirmation thus creating a “connection” between two peers. If a packet is corrupted a request is to the source for a replacement. Because there is a need to acknowledge all sent packets and error correction, TCP becomes bulkier and slower than UDP but extremely reliable.

In Java, to implement TCP communication the following objects from the* package are used: Socket and ServerSocket. Other needed objects, from the* package: InputStream and OutputStream.

As you can see in Java there is such a thing as a Server and Client. A ServerSocket can be looked at as a Socket generator. Its accept method accepts an incoming connection from a client creating and returning a Socket object.

How to use a Socket
Socket aSocket = new Socket( server, port );

Reading from the socket

InputStream is = aSocket.getInputStream();
Scanner in = new Scanner( is );
( ... )

For more information on how to use a Scanner please refer to here.

Writing to the socket

OuputStream os = aSocket.getOutputStream();
byte[] message = new String( "Hello World!" ).getBytes();
os.write( message );

Closing a socket


How to use a ServerSocket

ServerSocket server = new ServerSocket( port );
Socket aSocket = server.accept();

The accept method is blocking, it will block the current execution flow. If there is need to process multiple clients at the same time the program must be multithreaded.

As we can observe, opposing UDP, the TCP approach, at least in Java, does not need a crafting of every single packet, there is an abstraction layer that makes it possible to just dump information and let the underlying implementation handle the low-level management.

For more information on TCP go here.

Thank you for reading!