Java network socket
Intended learning outcomes
- TCP/IP Networking Model
- Understand the use of socket and reliable TCP protocol.
- Learn to establish TCP connection by using the Socket and ServerSocket class.
- Learn to handle multiple connections by multi-threaded programming.
- Understand the use of datagram and non-guaranteed UDP protocol.
- Learn to communicate in UDP by using DatagramPacket and DatagramSocket.
- IP Multicasting and Multicast Group
- Learn to use MulticastSocket to send and receive broadcast messages.
TCP/IP networking model
Have four layers of this model:
Application layer:providing process-to-process data exchange for applications
Transport layer:handling host-to-host communication
(TCP,UDP,RTP,SCTP)
Internet layer:providing internetworking between independent networks define the addressing and routing structures(IP,ICMP)
Link layer:containing communication methods for data that remains within a single network segment(ARP,PPP,MAC)
Other layers of TCP/IP:physical layer, session layer,presentation layers
Connection-Orientd vs Connectionless
This function in the transport layer(can be categorized:TCP and UDP)
- Connection-Oriented:TCP
- Connectionless:UDP
Then let us analyse differences between two ways:
TCP | UDP |
---|---|
reliable protocol | Unreliable protocal |
Keep track of lost packets and make sure they are resent | does’t keep track or lost packets |
FIFO | not care the order of arrival packets |
Slow and require more computer resource | Fast and use less computer resources |
Supprot flow control | no flow control |
Used by critical applications | used by real-time applications |
Network Socket
- A network socket is an endpoint of an inter-process communication flow across a computer network(进程间通信流的端点)(Similar to the java file object that provides an endpoint for read and write to a file)
- A socket is bound to a port number so that the transport layer can identify the application that data is destined to be sent.(传输层识别数据要发送的app)
- When a client attempts to make connection with a particular server program, it supplies the port number of the associated service and the host address. The host machine examines the port number and passes the client’s request to the appropriate server program for processing.
- Many clients can be connected to a server(多对一)The server distinguish the clients via the use of sockets.
- A client want to connect with a server, it creates a socket at its end of the communication link,Upon receiving the client’s request, server will create a new socket at its end that will be dedicated to communication with that particular client.
- Each TCP/IP or UDP/IP connection is uniquely defined by a 5-tuple:Source Address,Source Port Number,Destination Address,Destination port number and Protocal
socket communications in Java
- A socket is a bi-directional communication channel.(most fundamental means for client-server communications across the network)
- There are 2 types of sockets in java:
- Stream sockets(Connection-Oriented backed by TCP)
- Datagram Sockets(Conectionless,backed by UDP)
- The socket API is full duplex(全双工)-both client and server can send and receive at the same time.
- The socket operations at the client side are slightly different from those at the server side.
Stream Socket(code block)
Difference at two endpoint
Operation at server side | Operation at client side |
---|---|
A server is always waiting for incoming connection requests. So a server socket only specifies its own port number. | A client needs to specify both host address and port number of the server. |
Creare a server socketServerSocket(port) ServerSocket s=new ServerSocket(8888); | Create a client socketSocket(host,port) Socket s=new Socket("baidu.com",8888); |
Accept an incoming connectionSocket snew=s.accept(); | Close a Sockets.close(); |
Read/Write Through a Socket
- Get I/O data streams out of the socket s:
InputStream ins = s.getInputStream();
OutputStream outs = s.getOutputStream();
Note, “ins” and “outs” are of the same type as “System.in” and
“System.out”
- Get I/O reader and writer:
BufferedReader in = new BufferedReader(new inputStreamReader(ins));
PrintWriter out = new PrintWriter(outs, true); // “true” makes socket auto-flush in every print
- Read / write to I/O reader or writer:
String str = in.readLine(); // end when meeting ‘\r’
out.println( “Echo:” + str + “\r”);
Multi-thread Server Implementations
The EchoServer always blocked by the readLine() I/O operation and
cannot accept new connections.
We can put these two tasks into different threads to let it handle more clients concurrently.
- The server waits all the time for new client connections at the server socket by accept().
- Each time when a connection accepted, the server spawns a new thread to handle the incoming connection, and itself is back waiting for new connections(start()).
while (true) {
Socket incoming = s.accept( ); // wait here all the time
new HandlerThread(incoming).start();
}// return immediately
A thread dies after serving a client’s connection.
Datagram Socket
- Not care whether receive the data, it just knows the speed is faster.
- Some applications that you write to communicate over the network will not require the reliable, point-to-point channel provided by TCP. Rather, your applications might benefit from a mode of communication that delivers independent packages of information whose arrival and order of arrival are notguaranteed.
- The UDP protocol provides a mode of network communication whereby
applications send packets of data, called datagrams, to one another.A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. - The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent datagram communication using UDP.
Datagram Packet
- Java datagram sockets are connectionless.
- DatagramPacket has these parts:
- sender’s IP (InetAddress) and port no.
- receiver’s IP and port no.
- a byte array of data
- the length of data (no. of byte)
- InetAddress can be constructed by:
hostname - the specified host
address - the raw IP address in network byte order (big endian byte order)
- An InetAddress object can be created by:
InetAddress addr = InetAddress.getByName(“www.google.com”);
//or
byte [] b = new byte[] {(byte)127,(byte)0,(byte)0,(byte)1};
InetAddress addr = InetAddress.getByAddress(b);
Datagram Structure
Sending Datagram packet
We need to construct a DatagramPacket with the following:
Destination address: IP and port
Data: byte array
DatagramPacket(byte buffer[], int len, InetAddress dest_ip, int dest_port)
String s = "This is a test of UDP Datagram sockets.";
byte [] data = s.getBytes(); // convert a string to an array of bytes to fit in a packet
try {
InetAddress addr = InetAddress.getByName(“example.com");
} catch (UnknowHostException e) {
System.out.println(e);
}
int port = 33333;
DatagramPacket outp = new DatagramPacket(data, data.length, addr, port);
- The maximal size of a datagram packet is 64K (16-bit length, including UDP & IP headers). The typical Ethernet transfer units are 1500 bytes and
9000 bytes, it’s a good compromise to pick the datagram packet size to be ~1472 bytes or 8000 bytes to avoid fragmentation.
Receiving Datagram Packet
- We need to construct a DatagramPacket for storing an incoming packet:
DatagramPacket(byte buffer[], int len)
A DatagramPacket contains both data and address, use the following methods to get information out of a DatagramPacket object:
public InetAddress getAddress()
//it returns the remote host IP address. It returns the sender’s host IP address if it is a received datagram and the receiver’s host address if it’s a datagram to be sent.
public int getPort()
//it returns the port number of the remote address of a datagram,similar to “getAddress()”.
public int getLength()
//it returns the number of bytes of the data in the datagram (not include the header).
public byte[] getData()
//it returns a byte array in the datagram. The number of bytes in the array should equal to the value returned from “getLength()”.
- You often need the following methods to convert a byte array into a string when
processing a received datagram:
public String String(byte[] array) // convert a whole array
public String String(byte[] array, int offset, int length)
Datagram Socket
- Since the addresses are already embedded in datagrams, a datagram socket is simply an endpoint for sending/receiving datagrams.
Construct a socket at server side | Construct a socket at client side |
---|---|
public DatagramSocket(int port) | public DatagramSocket( ) |
The port number will be used by senders to send datagrams to this socket. | The client port number is assigned randomly. The server’s address &port number is embedded in datagrams. |
- Send / Receive DatagramPackets
public void send(DatagramPacket dp)
public void receive(DatagramPacket dp)
Multicasting
- A multicast group is specified by a class D IP address and a standard UDP port number.
- When one sends a message to a multicast group, all subscribing recipients to that host and port receive the message.
- A MulticastSocket is a subclass of DatagramSocket, with
additional capabilities for joining groups of other multicast hosts on the internet. - Multicast datagram socket can be used for sending and receiving IP multicast packets.
Multicast Socket
- Rewrite the quote server so that it multicasts DatagramPackets to multiple recipients.
- Instead of sending quotes to a specific client that makes a request, the new server now needs to multicast quotes at a regular interval.
//It can use an ordinary DatagramSocket to send packets
//to a multicast group address (e.g. 230.0.0.1),
//not necessary to be a member.
- The client needs to be modified so that it passively listens for quotes on a MulticastSocket.
//Construct a socket at Client side
public MulticastSocket(int)
//The port number will be used by senders to send datagrams to this socket
//Join/Leave a multicast group
public void joinGroup(InetAddress)
//or
public void joinGroup(SocketAddress, NetworkInterface)
public void leaveGroup(InetAddress)
//or
public void leaveGroup(SocketAddress, NetworkInterface)