Home>

1 Introduction to java socket

The so-called socket is often called "socket", which is used to describe the IP address and port.Is a handle to a communication chain.Applications usually make requests to the network or respond to network requests through "sockets".The socket and serversocket libraries are in the java.net package. serversocket is used on the server side,A socket is used when establishing a network connection.When the connection is successful,A socket instance will be generated at both ends of the application. Operating this instance,Complete the required session.For a network connection,Sockets are equal,There is no difference,Do not create different levels because 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 side,Singleton pattern
 * @author xiang
 *
 * /
public class tcpserver implements runnable {
  private static final logger logger=loggerfactory.getlogger (tcpserver.class);
  //Member variables/
  private static tcpserver serverinstance;
  private static map<string, socketthread>socketmaps=new hashmap<string, socketthread>();//Each client connection will create a new socketthread corresponding to it private static serversocket serversocket;//server socket
  private static int serport=9999;//server port number
  private static boolean flag;//Server status flag
  private static final int buffer_size=512;//data receiving character array size
  //Constructor/
  private tcpserver () {
  }
  /**
   * Get examples
   * @return tcpserver instance serverinstance
   * /
  public static tcpserver getserverinstance () {
    if (serverinstance == null)
      serverinstance=new tcpserver ();
    return serverinstance;
  }
  /**
   * Turn on the 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 []:array of characters to be sent
   * @param key The client's key. If it is empty or "", it means the data is sent in batches.
   * @throws ioexception
   * /
  public void sendmessage (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 client's key. If it is empty or "", it means the data is sent in batches.
   * @param msgstr:string to send
   * @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 ("The server thread is already started");while (true) {
      try {
        while (flag) {
          logger.info ("The server thread is in the listening state");
          socket socket=serversocket.accept ();
          string key=socket.getremotesocketaddress (). tostring ();
          socketthread thread=new socketthread (socket, key);
          thread.start ();
          socketmaps.put (key, thread);
          logger.info ("A client is connected:" + key);
        }
      } catch (exception e) {
        e.printstacktrace ();
      }
    }
  }
  /**
   * Handling the data receiving request after 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,Release resources
     * @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 [] receivbuf=new byte [buffer_size];
      int recvmsgsize;
      try {
        in=socket.getinputstream ();
        out=socket.getoutputstream ();
        while ((recvmsgsize=in.read (receivbuf))!=-1) {
          string receiveddata=new string (receivbuf, 0, recvmsgsize);
          system.out.println ("reverve form [port" + socket.getport () + "]:" + receiveddata);
          system.out.println ("now the size of socketmaps is" + socketmaps.size ());
          /************************************************* *************
           *
           * Processing after receiving data
           *
           ************************************************** ************ /
        }
        //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 () + "] Reply to client's message sent successfully");
        closeconnect ();
        socketmaps.remove (key);
      } catch (exception e) {
        e.printstacktrace ();
        try {
          closeconnect ();
        } catch (ioexception e1) {
          e1.printstacktrace ();
        }
      }
    }
    ////////////////
    public int getport () {
      return socket.getport ();
    }
  }
  //. end socketthread
}
  • Previous Ioc (inversion of control) and Di (dependency injection) in php
  • Next vue20 multi-criteria search component use in detail