Socket programming in Java allows programs to communicate over a computer network. A socket provides an interface to send and receive data through ports on a host. The core java.net package contains classes for network programming including Socket, ServerSocket, DatagramSocket, and InetAddress. TCP sockets provide connection-oriented reliable data streams while UDP sockets provide unreliable datagram-based communication. Examples show how to create server and client sockets to exchange data for both TCP and UDP.
4. Ports in socket
Each host has 65,536 ports
Some ports are reserved for specific apps
A socket provides an interface to send data
to/from the network through a port
9. Example of t.c.p socket
Server
• Create a ServerSocket object
ServerSocket servSocket = new
ServerSocket(1234);
• Put the server into a waiting
state
Socket link =
servSocket.accept();
• Set up input and output streams
• use thread to serve this client
via link
• Send and receive data
out.println(awaiting data…);
String input = in.readLine();
• Close the connection
link.close()
10. Example of t.c.p socket
Client
• Establish a connection to the
server
Socket link =
new
Socket(<server>,<port>);
• Set up input and output
streams
• Send and receive data
• Close the connection
12. Example of u.d.p socket
SERVER
•Create a DatagramSocket object
DatagramSocket dgramSocket =
new DatagramSocket(1234);
•Create a buffer for incoming datagrams
byte[] buffer = new byte[256];
•Create a DatagramPacket object for the incoming
datagram
•DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
•Accept an incoming datagram
dgramSocket.receive(inPacket)
•Accept the sender’s address and port from the packet
InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();
•Retrieve the data from the buffer
string message =
new String(inPacket.getData(), 0,
inPacket.getLength());
•Create the response datagram
•DatagramPacket outPacket =
new DatagramPacket(
response.getBytes(),
response.length(),
clientAddress, clientPort);
•Send the response datagram
dgramSocket.send(outPacket)
•Close the DatagramSocket: dgram.close();
13. Example of u.d.p socket
CLIENT
• Create a DatagramSocket object
DatagramSocket dgramSocket = new
DatagramSocket;
• Create the outgoing datagram
DatagramPacket outPacket =
• new DatagramPacket(message.getBytes(),
message.length(),host, port);
• Send the datagram message
dgramSocket.send(outPacket)
• Create a buffer for incoming datagrams
byte[] buffer = new byte[256];
• Create a DatagramPacket object for the incoming
datagram
• DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
• Accept an incoming datagram
dgramSocket.receive(inPacket)
• Retrieve the data from the buffer
string response = new String(inPacket.getData(), 0,
inPacket.getLength());
• Close the DatagramSocket:
dgram.close();