Java Socket implements multi-thread Communication Based on TCP and UDP, and socketudp

Source: Internet
Author: User

Java Socket implements multi-thread Communication Based on TCP and UDP, and socketudp

1. Implement TCP programming through Socket

1.1 TCP Programming

TCP is connection-oriented, reliable, and ordered. Data is sent in byte streams. The TCP-based Network Communication classes include the client Socket class and the server ServerSocket class.

1.2 server routine

1. Create a ServerSocket object and bind it to the listening port.

2. Use the accept () method to listen to client requests.

3. After the connection is established, the request information sent by the client is read through the input stream.

4. Send Response Information to the client through the output.

5. Close the response resource.

1.3 client routine

1. Create a Socket object to specify the address and port number of the server to be connected.

2. After the connection is established, send the request information to the server through the output.

3. Get the server response information through the input stream.

4. Close the corresponding resource.

1.4 multi-threaded communication steps between servers and multiple clients

1. The server creates a ServerSocket and calls accept () cyclically to wait for the client to connect.

2. The client creates a socket and requests a connection with the server.

3. The server accepts client requests and creates a socket to establish a leased line connection with the customer.

4. The two sockets that establish the connection talk to each other in a separate thread.

5. The server continues waiting for a new connection.

1.5 create a processing thread type ServerThread

Here we choose to implement the runnable interface instead of inheriting Thread because a class can only inherit one parent class. When I need to inherit other classes, the parent class will not be easy to handle.

  

Package com. tzzh; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java. io. printWriter; import java.net. socket; public class ServerThread implements Runnable {Socket socket = null; // Socket public ServerThread (Socket socket) {this. socket = socket ;}@ Override public void run () {InputStream is = Null; InputStreamReader isr = null; BufferedReader br = null; OutputStream OS = null; PrintWriter pw = null; try {// communicates with the client to obtain the input stream, reads the information provided by the client is = socket. getInputStream (); isr = new InputStreamReader (is, "GBK"); br = new BufferedReader (isr); String data = null; while (data = br. readLine ())! = Null) {// cyclically read client information System. out. println ("I Am a server and the client submits the following information:" + data);} socket. shutdownInput (); // close the input stream // obtain the output stream and respond to the client request OS = socket. getOutputStream (); pw = new PrintWriter (OS); pw. write ("server-side response successful! "); Pw. flush ();} catch (IOException e) {e. printStackTrace ();} finally {// close the resource that is related to socket try {if (pw! = Null) pw. close (); if (OS! = Null) OS. close (); if (br! = Null) br. close (); if (isr! = Null) isr. close (); if (is! = Null) is. close (); if (socket! = Null) socket. close () ;}catch (IOException e) {e. printStackTrace ();}}}}

 

1.6 create a server class

You can use while to listen for connection requests from different clients cyclically. Because this is an endless loop, there is no need to close it or there is no chance to close serverSocket. Set the count value to record the number of times the server has been connected and display the ip value of the client. If the Thread processing class inherits the Thread class, you can change the code for creating a new Thread to ServerThread serverThread = new ServerThread (socket); serverThread. start ();

Package com. tzzh; import java. io. IOException; import java.net. inetAddress; import java.net. serverSocket; import java.net. socket; public class Server {public static void main (String [] args) {try {// create a Server Socket, that is, ServerSocket, bind the port ServerSocket serverSocket = new ServerSocket (8888); Socket socket = null; // record the number of clients connected to the server int count = 0; System. out. println ("*** the server is about to start, wait for the client connection ***"); while (true) {// listen cyclically to the connection of the new client // call accept () method to listen, wait for the client connection to obtain the Socket instance socket = serverSocket. accept (); // create a new Thread thread Thread = new thread (new ServerThread (socket); Thread. start (); count ++; System. out. println ("Number of server connections:" + count); InetAddress address = socket. getInetAddress (); System. out. println ("current client IP:" + address. getHostAddress ();} // serverSocket. close (); Keep loop listening, do not close the connection} catch (IOException e) {e. printStackTrace ();}}}

1.7 create a client class

In subsequent resource close operations, I commented out the input/output-related stream because the input/output stream is also closed when the Socket is closed for the same socket, you just need to close the socket directly. Of course, it is okay to keep it.

Package com. tzzh; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java. io. printWriter; import java.net. socket; import java.net. unknownHostException; public class Client {public static void main (String [] args) {try {// create a Client Socket, specify the server address and port Socket socket = new Socket ("localhost ", 8888); // after the connection is established, get and enter Output stream: sends the OutputStream OS = socket to the server. getOutputStream (); // The output stream is packaged as the print stream PrintWriter pw = new PrintWriter (OS); // send the message pw to the server. write ("username: zzh; Password: 123"); // write to the memory buffer pw. flush (); // refresh the cache and output the socket information to the server. shutdownOutput (); // close the output stream // obtain the input stream and receive the server response information. InputStream is = socket. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is, "GBK"); String data = null; while (data = br. readLine ())! = Null) {System. out. println ("I Am a client and the server submits the following information:" + data);} // close other resources // br. close (); // is. close (); // pw. close (); // OS. close (); socket. close ();} catch (UnknownHostException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

 

1.8 run the server first.

 

In this case, check the server console: the server continuously listens for client connections.

 

1.9 connect the second client

Modify the user name zzh to admin. Run the client and open the server console.

  

The ip address of the output client is 127.0.0.1, because the server and client are both local and the ip address of the client is displayed in the real environment.

 

Ii. UDP programming through Socket

2.1 UDP Programming

UDP is also called the User Datagram Protocol, which is connectionless, unreliable, and unordered. The characteristic is that the transmission speed is relatively fast. UDP uses datagram as the data transmission carrier. For data transmission, you must first define the data to be transmitted as a data packet, and specify the Socket (host address and port number) to be transmitted in the data packet ), then, send the datagram. Related operation classes include the mongorampacket datagram package and the mongoramsocket class for end-to-end communication.

2.2 server implementation routine

1. Create an initramsocket and specify the port number. 2. Create an ingress rampacket. 3. receive data sent by the client. 4. Read data.

2.3 client implementation routine

1. Define the sending information, such as the sending Address, port number, and content. 2. Create an ingress rampacket that contains the information to be sent. 3. Create a DatagramSocket. 4. Send data.

2.4 multi-threaded communication steps between servers and multiple clients

1. The server creates the instance socket of the initramsocket and calls the receive () method cyclically. This method will be blocked until the datagram is received.

2. Create a mongoramsocket on the client and send the datagram packet containing the address, port number, and content.

3. The server receives the data packet and establishes a thread with the client through DatagramSocket and packet.

4. The server continues to wait for the new data packet.

5. the sender's mongorampacket constructor transmits four parameters including data content, data size, address, and port number. The receiver rampacket constructor has two parameters: the received data and the data size.

2.5 create a server thread processing class UDPThread

Note: The instance socket of mongoramsocket cannot be closed, and SocketException may occur. The new String (packet. getData (), 0, packet. getLength () used to read data. The parameter indicates the byte array, position, and length of the data.

Package com. uzzh; import java. io. IOException; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UDPThread implements Runnable {DatagramSocket socket = null; DatagramPacket packet = null; public UDPThread (DatagramSocket socket, DatagramPacket packet) {this. socket = socket; this. packet = packet ;}@ Override public void run () {String info = null; Ine TAddress address = null; int port = 8800; byte [] data2 = null; DatagramPacket packet2 = null; try {info = new String (packet. getData (), 0, packet. getLength (); System. out. println ("I Am a server, the client said:" + info); address = packet. getAddress (); port = packet. getPort (); data2 = "I'm responding to you! ". GetBytes (); packet2 = new DatagramPacket (data2, data2.length, address, port); socket. send (packet2);} catch (IOException e) {e. printStackTrace ();} // socket. close (); cannot close }}

 

2.6 create a server class

  

Package com. uzzh; import java. io. IOException; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UDPServer {public static void main (String [] args) throws IOException {DatagramSocket socket = new DatagramSocket (8800); DatagramPacket packet = null; byte [] data = null; int count = 0; System. out. println ("*** server startup, waiting for data sending ***"); while (true) {data = new byte [1024]; // create a byte array, packet = new DatagramPacket (data, data. length); socket. receive (packet); // This method will always block Thread thread = new Thread (new UDPThread (socket, packet); thread. start (); count ++; System. out. println ("Number of times the server has been connected:" + count); InetAddress address = packet. getAddress (); System. out. println ("current client IP:" + address. getHostAddress ());}}}

 

Previously, I put the new initramsocket into the while loop and reported java.net. BindException: Address already in use: Cannot bind. Only then can I know that the new initramsocket object Cannot be created continuously in the while.

2.7 create a client class

Package com. uzzh; import java. io. IOException; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UDPClient {public static void main (String [] args) throws IOException {// defines the server address, port number, and data InetAddress address = InetAddress. getByName ("localhost"); int port = 8800; byte [] data = "username: admin; Password: 123 ". getBytes (); // convert the string to a byte array // create the datagram DatagramPacket packet = new DatagramPacket (data, data. length, address, port); // create a DatagramSocket to send and receive data; // send a datagram socket to the server. send (packet); // receives the Server Response Data byte [] data2 = new byte [1024]; DatagramPacket packet2 = new DatagramPacket (data2, data2.length); socket. receive (packet2); String info = new String (data2, 0, packet2.getLength (); System. out. println ("I Am a client, the server says:" + info); socket. close ();}}

 

2.8 run the server first.

2.9 modify client information and run the client again

 

Server console: the server has been waiting for the client to receive data cyclically.

 

Iii. Summary

These two examples simply implement socket programming based on TCP and UDP, and the priority of Multithreading is not considered yet, the Server communicates with multiple clients because it is an endless loop and does not set the multi-thread priority. This may lead to a very slow running speed. The priority range is 1-10 and the default value is 5, we can appropriately reduce the thread priority, such as thread. setPriority (4 );

For the same socket, if the output stream is disabled, for example (pw. close (), and the socket associated with the output stream will also be closed, so generally the output stream does not need to be closed. When the socket is closed, the output stream will also be closed, simply close the socket.

When transmitting information through TCP communication, it is transmitted in the form of objects. You can use ObjectOutputStream object to serialize the stream to transmit objects, such as ObjectOutputStream OS = new ObjectOutputStream (socket. getOutputStream (); User user = new User ("admin", "123"); OS. writeObject (user );

I hope this article will help you get something. Please like it or follow me. Thank you for watching it!

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.