Programming of TCP/UDP network communication in Java

Source: Internet
Author: User
Tags string back

127.0.0.1 is the loop address for testing, equivalent to localhost native address, no network card, no DNS can be accessed.

The port address is between 0~65535, where the port between 0~1023 is used for some well-known network services and applications, and the user's normal network application should use more than 1024 of the port.

Network applications are basically TCP (Transmission Control Protocol Transmission Protocol) and UDP (User Datagram Protocol Subscriber Datagram Protocol), TCP is a connection-oriented communication protocol, UDP is a non-connected communication protocol.

Socket connection sockets, Java provides the corresponding classes for TCP and UDP, TCP is. ServerSocket (for server side) and. Sockets (for clients); UDP is. Datagramsocket.

1,java writing a UDP network program

1.1,datagramsocket

Datagramsocket has the following construction methods:

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 that binds it to the specified local address. Specifies that the NIC sends and receives data.

If the IP address of the network card is not specified when the Datagramsocket object is created, when the data is sent, the underlying driver automatically selects a network card to send, and when it receives the data, it receives all the data that the NIC receives consistent with the port.

When sending a message, you can specify the port number when you receive the message without specifying the port number, because you want to receive the specified data.

Send data using the Datagramsocket.send (Datagrampacket p) method to receive data using the Datagramsocket.receive (Datagrampacket p) method.

1.2,datagrampacket

The Datagrampacket class has the following construction methods:

1,datagrampacket (byte[] buf, int length): Constructs a datagrampacket to receive packets of length.

2,datagrampacket (byte[] buf, int length, inetaddress address, int port): Constructs a datagram package that is used to send packets of length to the specified port number on the specified host.

The first construction method is used when the data is received, and the second construction method is used when sending the data.

1.3,inetaddress

The class that wraps the IP address in Java,

Datagrampacket.getaddress () can get the IP address of the sending or receiving party. Datagrampacket.getport () can get the port of the sending or receiving party.

1.4,UDP Program Examples

Send program:

Import. Datagrampacket;

Import. Datagramsocket;

Import. 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 connection

}

}

Receiving program:

Import. Datagrampacket;

Import. 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 ();

}

}

Test to run the receiving program before running the sender. If the receiving program does not receive data, it will block until the program is closed. If no data is sent over the network, the receiving program is not blocked, usually using a port that has already been occupied.

2,java writing a TCP network program

2.1,serversocket

The first thing to do is to write a TCP Network service program. The ServerSocket class is used to create a server socket. Its common construction methods are:

1,serversocket (int port): Creates a server socket bound to a specific port.

2,serversocket (int port, int backlog): Creates a server socket and binds it to the specified local port number, using the specified backlog (the number of waiting clients to keep the connection request when the server is busy).

3,serversocket (int port, int backlog, inetaddress bindaddr): Creates a server with the specified port, the listening backlog, and the local IP address to bind to.

2.2,socket

To establish a connection to the server, the client must first create a socket object, which is commonly constructed by:

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 for the specified IP address.

3,socket (inetaddress address, int port, inetaddress localaddr, int localport): Creates a socket and connects it to the specified remote address on the specified remote port.

4,socket (String host, int port, inetaddress localaddr, int localport): Creates a socket and connects it to the specified remote port on the specified remote host.

For common applications, it is very simple and convenient to use the 1th construction method to create a client socket object and establish a connection to the server.

The server-side program calls the Serversocket.accept method to wait for a connection request from the client, and once accept receives the client connection request, the method returns a socket object that establishes a leased line connection to the client. Do not use the program to create the socket object. The two sockets that are connected are data exchanged in IO streams, and Java provides the input stream object that Socket.getinputstream returns the socket. Socket.getoutputstream returns the output stream object of the socket.

2.3,TCP program Examples of server programs:

Import Java.io.InputStream;

Import Java.io.OutputStream;

Import. ServerSocket;

Import. 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 is created that waits for a connection on port 8000, and when a client's connection request is received, the program obtains an input and output stream object from the socket object that the client has established a connection to, and sends a string of characters to the client through the output stream first. It then reads the information sent by the client through the input stream, prints the information, and then closes all resources.

To run the server program before you can run the client program, when the TCP server program runs to the Socket.accpet () method to wait for the client to connect, the Accept method will block until a client connection request arrives, the method will return, if no request arrives, and there is no blocking, A port that is already occupied is usually used.

We can use the Telnet tool provided by Windows to test the server program in a command-line window: The command is as follows: Telnet localhost 8000

As you can see, Telnet is sent as long as there is input, so if we want to read more than one character at a time on the server, we need to work on it further and look at the following code:

Import Java.io.BufferedReader;

Import Java.io.InputStream;

Import Java.io.InputStreamReader;

Import Java.io.OutputStream;

Import. ServerSocket;

Import. 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 InputStreamReader (IPS)); InputStream is packaged and the cache is added

OutputStream Ops = S.getoutputstream ();

Ops.write ("hello,world!"). GetBytes ());

System.out.println (Br.readline ());

Br.close (); Closing the wrapper class will automatically close the base class inside

Ops.close ();

S.close ();

Ss.close ();

}

}

Again using the Telnet tool can be seen, this time can send more than one character, press ENTER after sending data to the server side.

2.4,TCP Program Example Improved server program:

In most cases, the server has to serve multiple clients, but a single accept method call receives only one connection, so the Accept method is placed in a looping statement so that multiple connections can be received. The data interchange code for each connection is also placed in a loop, This ensures that the data can be exchanged continuously.

The data interchange code for each connection must be run in a separate thread, otherwise it will not be possible to execute other program code while the code is running, and the Accept method will not be called and the new connection will not enter.

Here is an example where the client sends a string to the server, and the server reverses all the characters in the string 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. ServerSocket;

Import. 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. inetaddress;

Import. 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 see which ports have been used.

Programming of TCP/UDP network communication in Java

Related Article

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.