Week 77 — How can one create a TCP connection in a Java application?
Question of the Week #77
How can one create a TCP connection in a Java application?
7 Replies
The
Socket
class can be used to connect to a specified host/IP and port combination via TCP: A connection can be established using the Socket
constructor and data can be read/written using Socket#getInputStream
/Socket#getOutputStream
.
Similarly, it is possible to accept TCP connections using the ServerSocket
class. One can create a ServerSocket
listening for requests on some port and accept incoming requests by calling the accept
method. This method returns a Socket
that can be used for communicating with the connected client.
The following code listens for a connection on port 1337 and sends back all data it receives in that connection:
📖 Sample answer from dan1st
What you would especially need for this TCP connection in Java is to make use of the Socket and ServerSocket classes. The Socket class is used for the client and the server to identify each other and the ServerSocket is for the server to hold a server. Down below is an image of making the ServerSocket in the Server class to host the connection and underneath that is an image of the client class identifying the Server with the use of the Socket class.
Submission from hypyrcube
There are two methods in java to establis a connection.
1. connection less (UDP)
2. connection oriented(TCP)
this can be implemented using socket and serversocket class resided in java.net package.
we need to write two programs, cliend side and serversocket which also required inputdatastream and outputdatastream
Submission from chandrashekhar_
Socket and ServerSocket are used for TCP connections.
The connection is established when creating a
Socket
instance using a constructor that directly connects to one or by using a constructor that creates an unconnected Socket
and then by calling Socket#connect
.
To create a server that accepts tcp connections you can use the ServerSocket
and its ServerSocket#accept
method.Submission from squidxtv