Socket Programming
Socket Programming
1.Yyou need a host to connect to. We may or may not run the client(s) and
the server on the same machine..
2.TCP/IP port that the program is going to be communicating on. TCP/IP uses
ports because it is assumed that servers will be doing more than one
network function at a time and ports provide a way to maange this.
Note:TCP/IP uses ports because it is assumed that servers will be doing more than one network
function at a time and ports provide a way to maange this.
For example: a server may be serving up web pages (port 80), it may have a
FTP (port 21) server, and it may be handling a SMTP mail server (port 25).
Ports are assigned by the server. The client needs to know what port to use
for a particular service. In the TCP/IP world, each computer with a TCP/IP
address has access to 65,535 ports. Keep in mind that ports are not physical
devices like a serial, parallel, or USB port. They are an abstraction in the
computer’s memory running under the TCP/IP transport layer protocol.
Client programming:When programming a client, you must follow these four steps:
• Open a socket.
• Open an input and output stream to the socket.
• Read from and write to the socket according to the server's protocol.
• Clean up.
• algorithm for TCP client
o Find the IP address and port number of server
o Create a TCP socket
o Connect the socket to server (Server must be up and listening for
new requests)
o Send/ receive data with server using the socket
o Close the connection
• algorithm for TCP server
o Find the IP address and port number of server
o Create a TCP server socket
o Bind the server socket to server IP and Port number (this is the
port to which clients will connect)
o Accept a new connection from client
returns a client socket that represents the client which is
connected
o Send/ receive data with client using the client socket
o Close the connection with client
How to create an input stream?On the client side, you can use the
DataInputStream class to create an input stream to receive response
from the server:The class DataInputStream allows you to read lines of
text and Java primitive data types in a portable way. It has methods
such as read, readChar, readInt, readDouble, and readLine,.
• On the server side, you can use DataInputStream to receive input from
the client:
• How to create an output stream?On the client side, you can create
an output stream to send information to the server socket using the
class PrintStream or DataOutputStream of java.io:
• How to close sockets?You should always close the output and input
stream before you close the socket
•