Lt9-Java Network Socket

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:

TCPUDP
reliable protocolUnreliable protocal
Keep track of lost packets and make sure they are resentdoes’t keep track or lost packets
FIFOnot care the order of arrival packets
Slow and require more computer resourceFast and use less computer resources
Supprot flow controlno flow control
Used by critical applicationsused 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:
  1. Stream sockets(Connection-Oriented backed by TCP)
  2. 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 sideOperation 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.

  1. The server waits all the time for new client connections at the server socket by accept().
  2. 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:
  1. sender’s IP (InetAddress) and port no.
  2. receiver’s IP and port no.
  3. a byte array of data
  4. 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 sideConstruct 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)
  • 25
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值