TCP/UDP network communication programming in Java

Source: Internet
Author: User

Basically, network applications are TCP (Transmission Control Protocol) and UDP (User datasync protocol User Datagram Protocol). TCP is a connection-oriented communication protocol, UDP is a connectionless communication protocol.

127.0.0.1 is the loop address used for testing. It is equivalent to the local address of localhost. It can be accessed without a NIC or DNS.

The port address ranges from 0 ~ Between 65535, 0 ~ Ports between 1023 are used for some well-known network services and applications. Your common network applications should use ports above 1024.

Socket connects to the socket. Java provides the corresponding classes for TCP and UDP respectively. TCP is java.net. serversocket (for server) and java.net. socket (for the client); UDP is java.net. datagramsocket.

1. Write UDP network programs in Java

1.1, datagramsocket

Datagramsocket has the following constructor:
1. datagramsocket (): constructs a datagram socket and binds it to any available port on the local host.
2. datagramsocket (INT port): Creates a datagram socket and binds it to the specified port on the local host.
3. datagramsocket (INT port, inetaddress laddr): Creates a datagram socket and binds it to the specified local address. That is, specify the NIC to send and receive data.

If the IP address of the network adapter is not specified when the initramsocket object is created, the underlying driver automatically selects a network adapter to send the data. When receiving the data, all NICs receive the same data as the port.

When sending information, you can choose not to specify the port number. When receiving information, you must specify the port number because you want to receive the specified data.

Use the datagramsocket. Send (datagrampacket p) method to send data, and use the datagramsocket. Receive (datagrampacket p) method to receive data.

1.2, datagrampacket

The datagrampacket class has the following constructor:
1. mongorampacket (byte [] Buf, int length): Constructs mongorampacket to receive data packets with length.
2. mongorampacket (byte [] Buf, int length, inetaddress address, int port): constructs a datagram packet to send a packet with length to the specified port number on the specified host.

The first constructor is used to receive data, and the second constructor is used to send data.

1.3, inetaddress

Class for packaging IP addresses in Java,

Mongorampacket. getaddress () can get the IP address of the sender or receiver. mongorampacket. getport () can get the port of the sender or receiver.

1.4. UDP program example

Sender program:

Import java.net. datagrampacket; import java.net. datagramsocket; import java.net. inetaddress; public class udpsend {public static void main (string [] ARGs) throws exception {datagramsocket DS = new datagramsocket (); string STR = "Hello, world! "; Datagrampacket dp = new datagrampacket (Str. getbytes (), str. length (), inetaddress. getbyname ("192.168.0.105"), 3000); DS. send (DP); DS. close (); // close the connection }}

Receiver:

import java.net.DatagramPacket;import java.net.DatagramSocket;public class UdpRecv {public static void main(String[] args) throws Exception {DatagramSocket ds = new DatagramSocket(3000);byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);ds.receive(dp);String str = new String(dp.getData(),0,dp.getLength());System.out.println(str);System.out.println("IP:" + dp.getAddress().getHostAddress() + ",PORT:" + dp.getPort());ds.close();}}

Before testing, you must run the receiving program and then the sending program. if the receiving program does not receive data, it will be blocked until the program is closed after receiving the data. if no data is sent over the network and the receiving program is not blocked, A occupied port is usually used.

2. Write TCP network programs in Java

2.1, serversocket

To compile a TCP network service program, you must first use the java.net. serversocket class to create a server socket. Its common constructor methods include:
1. serversocket (INT port): Creates a server socket bound to a specific port.
2. serversocket (INT port, int backlog): Create a server socket and bind it to the specified local port number by using the specified backlog (the number of customers waiting for the connection request to be kept when the server is busy.
3. serversocket (INT port, int backlog, inetaddress bindaddr): Create a server using the specified port, listener backlog, and local IP address to bind.

2.2, socket

To establish a connection between the client and the server, you must first create a socket object. Its common constructor methods include:
1. socket (string host, int port): Creates a stream socket and connects it to the specified port number on the specified host.
2. socket (inetaddress address, int port): Creates a stream socket and connects it to the specified port number of the specified IP address.
3. socket (inetaddress address, int port, inetaddress localaddr, int localport): Create a socket and connect it to the specified remote address on the specified remote port.
4. socket (string host, int port, inetaddress localaddr, int localport): Create a socket and connect it to the specified remote port on the specified remote host.

For common applications, it is very simple and convenient to use the 1st constructor to create the socket object of the client and establish a connection with the server.

The server program calls serversocket. the accept method waits for the client's connection request. Once the accept receives the client's connection request, this method returns a socket object that has established a leased line connection with the client, without the need for a program to create this socket object. the two sockets with established connections exchange data in the form of Io streams. Java provides the socket. getinputstream returns the input stream object of the socket, socket. getoutputstream returns the output stream object of the socket.

2.3. The server program of the TCP program example:

import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(8000);Socket s = ss.accept();InputStream ips = s.getInputStream();OutputStream ops = s.getOutputStream();ops.write("hello,World!".getBytes());byte[] buf = new byte[1024];int len = ips.read(buf);System.out.println(new String(buf,0,len));ips.close();ops.close();s.close();ss.close();}}

In this program, a serversocket object waiting for connection on port 8000 is created. After receiving a connection request from a customer, the program obtains the input and output stream object from the socket object connected to this customer. The output stream first sends a string of characters to the client, and then reads the information sent by the client through the input stream, print the information and close all resources. you must first run the server program before running the client program. When the TCP server runs on the socket. the accept method is blocked when the accpet () method waits for the client to connect. The method will not return until a client connection request arrives. If no request arrives, and no blocking occurs, generally, an occupied port is used.
We can use the Telnet tool provided by windows to test the server program in the command line window: Command: Telnet localhost 8000
As you can see, Telnet can be sent as long as there is input. Therefore, if you want to read multiple characters at a time on the server side, you need to further process them. See the following code:

Import Java. io. bufferedreader; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. outputstream; import java.net. serversocket; import java.net. socket; public class tcpserver {public static void main (string [] ARGs) throws exception {serversocket Ss = new serversocket (8000); socket S = ss. accept (); inputstream IPS = S. getinputstream (); bufferedreader BR = new bufferedreader (new inputs Treamreader (IPS); // pack inputstream and add the cache outputstream Ops = S. getoutputstream (); ops. Write ("Hello, world! ". Getbytes (); system. out. println (BR. readline (); BR. close (); // close the packaging class, which will automatically close the base class ops. close (); S. close (); SS. close ();}}

Use the Telnet tool again to check that more than one character can be sent this time. Press enter to send data to the server.

2.4. The improved server program in the TCP program example:

In most cases, the server needs to serve multiple clients, but one accept method call only receives one connection. Therefore, put the accept method in a loop statement, in this way, you can receive multiple connections. the data exchange code for each connection is also placed in a loop so that the two can exchange data continuously.

The Data Exchange Code of each connection must be run in an independent thread. Otherwise, other program code cannot be executed during the code running, and the accept method cannot be called, new connections cannot enter.

The following is an example. The client sends a string to the server. The server reverse sorts all the characters in the string and sends them back to the client. The client enters "quit" and exits the program.

import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(8000);while(true){Socket s = ss.accept();new Thread(new Servicer(s)).start();}}}class Servicer implements Runnable{Socket s;public Servicer(Socket s){this.s = s;}public void run(){try{InputStream ips = s.getInputStream();OutputStream ops = s.getOutputStream();BufferedReader br = new BufferedReader(new InputStreamReader(ips));DataOutputStream dos = new DataOutputStream(ops);while(true){String strWord = br.readLine();if(strWord.equalsIgnoreCase("quit")){break;}String strEcho = (new StringBuffer(strWord).reverse().toString());dos.writeBytes(strWord + "------->" + strEcho + System.getProperty("line.separator"));}br.close();dos.close();s.close();}catch(Exception e){e.printStackTrace();}}}

2.5. TCP program example client program:

import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;public class TcpClient {public static void main(String[] args) throws Exception{if(args.length < 2){System.out.println("Usage:java TcpClient ServerIP ServerPort");return ;}Socket s = new Socket(InetAddress.getByName(args[0]),Integer.parseInt(args[1]));InputStream ips = s.getInputStream();OutputStream ops = s.getOutputStream();BufferedReader brKey = new BufferedReader(new InputStreamReader(System.in));DataOutputStream dos = new DataOutputStream(ops);BufferedReader brNet = new BufferedReader(new InputStreamReader(ips));while(true){String strWord = brKey.readLine();dos.writeBytes(strWord + System.getProperty("line.separator"));if("quit".equalsIgnoreCase(strWord)){break;}else{System.out.println(brNet.readLine());}}dos.close();brNet.close();brKey.close();s.close();}}

Run the server program first, and then use Java tcpclient 192.168.0.3 8000 on the command line to start the client program. We can start multiple client programs.

We can use the netstat tool to view the used Port

 

Reprinted please indicate the source of http://blog.csdn.net/shimiso welcome people of insight to join our technical exchange group: 173711587

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.