Socket Programming
Introduction to Socket Programming
This Post describes a very basic one-way client and server setup where clients connect, send messages to the server, and the server uses socket connections to display them. There are a lot of low-level things needed to make these work well, but the Java API network package is responsible for all of these, so programmers can easily do network programming.
Client Connection
Establish a Socket Connection
You need a socket connection to connect to other machines. Socket connection means that two machines have information about each other's network location (IP address) and TCP port. The java.net.Socket class represents a Socket.To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
- First argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code will run on single stand-alone machine).
- Second argument – TCP Port. (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and output the data.
Closing the Connection
The socket connection is explicitly closed when the message is sent to the server.
Server Connection
Establish a Socket Connection
To create a server application, you need two sockets.
- ServerSocket is waiting for a client request (when the client creates a new Socket ())
- Ordinary old socket used to communicate with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Closing the Connection
After finishing, it is important to close the connection by closing the socket as well as input/output streams.

Comments
Post a Comment