Java uses Socket to implement TCP server (an instance), sockettcp

Source: Internet
Author: User

Java uses Socket to implement TCP server (an instance), sockettcp

1 Introduction to Java Socket

The so-called socket is also called a "socket". It is used to describe the IP address and port and is a communication chain handle. Applications usually send requests to or respond to network requests through sockets. The Socket and ServerSocket class libraries are located in the Java. NET package. ServerSocket is used on the server side. Socket is used to establish a network connection. When the connection is successful, a Socket instance is generated at both ends of the application to complete the required session. For a network connection, sockets are equal and there is no difference, not because of different levels on the server side or on the client side.

2 TCPServer code example

Import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; import java. util. date; import java. util. hashMap; import java. util. map; import org. slf4j. logger; import org. slf4j. loggerFactory;/*** TCP server, Singleton mode * @ author xiang **/public class TCPServer implements Runnable {private static final Logger logger = LoggerFactory. getLogger (TCPServer. class); // member variable/private static TCPServer serverInstance; private static Map <String, SocketThread> socketMaps = new HashMap <String, SocketThread> (); // each client creates a SocketThread and the corresponding private static ServerSocket serverSocket; // server socket private static int serPort = 9999; // server port number private static boolean flag; // The server status flag is private static final int BUFFER_SIZE = 512; // the size of the Data receiving character array // constructor/private TC PServer () {}/*** get instance * @ return TCPServer instance serverInstance */public static TCPServer getServerInstance () {if (serverInstance = null) serverInstance = new TCPServer (); return serverInstance;}/*** enable server * @ throws IOException */public void openTCPServer () throws IOException {if (serverSocket = null | serverSocket. isClosed () {serverSocket = new ServerSocket (serPort); flag = true ;}}/*** shut down the server * @ Throws IOException */public void closeTCPServer () throws IOException {flag = false; if (serverSocket! = Null) serverSocket. close ();/* for (Map. entry <String, SocketThread> entry: socketMaps. entrySet () {System. out. println ("Key =" + entry. getKey () + ", Value =" + entry. getValue ();} */for (SocketThread value: socketMaps. values () value. closeConnect (); socketMaps. clear ();}/*** the server sends data to the client * @ param bytes []: The character array to be sent * @ param key the key of the client, if it is null or "", it indicates a group of data * @ throws IOException */public void sendMess Age (String key, byte [] msgBytes) {if (key = null | key. equals ("") {for (SocketThread value: socketMaps. values () value. sendMassage (msgBytes);} else {SocketThread thread = socketMaps. get (key); if (thread! = Null) thread. sendMassage (msgBytes);}/*** the server sends data to the client * @ param key the key of the client. If it is null or "", it indicates a mass data sending * @ param msgStr: the String to be sent * @ throws IOException */public void sendMessage (String key, String msgStr) {byte [] sendByte = msgStr. getBytes (); if (key = null | key. equals ("") {for (SocketThread value: socketMaps. values () value. sendMassage (sendByte);} else {SocketThread thread = socketMaps. get (key); if (thread! = Null) thread. sendMassage (sendByte) ;}@override public void run () {logger.info ("server thread started"); while (true) {try {while (flag) {logger.info ("the server thread is listening"); Socket socket = serverSocket. accept (); String key = socket. getRemoteSocketAddress (). toString (); SocketThread thread = new SocketThread (socket, key); thread. start (); socketMaps. put (key, thread); logger.info ("client connection:" + key) ;}} catch (Exception e) {E. printStackTrace () ;}}/ *** internal class of the Data receiving request after processing the connection * @ author xiang **/private class SocketThread extends Thread {private Socket socket; private String key; private OutputStream out; private InputStream in; // constructor public SocketThread (Socket socket, String key) {this. socket = socket; this. key = key;}/*** send data * @ param bytes * @ throws IOException */public void sendMassage (byte [] bytes) {try {If (out = null) out = socket. getOutputStream (); out. write (bytes);} catch (Exception e) {e. printStackTrace (); try {closeConnect ();} catch (IOException e1) {e1.printStackTrace ();} socketMaps. remove (key) ;}}/*** close the connection and release the resource * @ throws IOException */public void closeConnect () throws IOException {if (out! = Null) out. close (); if (in! = Null) in. close (); if (socket! = Null & socket. isConnected () socket. close () ;}@ Override public void run () {byte [] bytes Buf = new byte [BUFFER_SIZE]; int recvMsgSize; try {in = socket. getInputStream (); out = socket. getOutputStream (); while (recvMsgSize = in. read (encrypted BUF ))! =-1) {String inclueddata = new String (inclubuf, 0, recvMsgSize); System. out. println ("Reverve form [port" + socket. getPort () + "]:" + receivedData); System. out. println ("Now the size of socketMaps is" + socketMaps. size ()); /*************************************** ********* **************************************** * ************/} // response to client byte [] sendByte = "The Server has received ". getBytes (); // out. write (sendByte, 0, sendByte. length); out. write (sendByte); System. out. println ("To Cliect [port:" + socket. getPort () + "] The reply client message is successfully sent"); closeConnect (); socketMaps. remove (key);} catch (Exception e) {e. printStackTrace (); try {closeConnect ();} catch (IOException e1) {e1.printStackTrace ();}}} /// // public int getport () {return socket. getPort ();}}//. end SocketThread}

 

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.