Socket communication: The socket code is divided into the client and the server.
The Java SDK provides some relatively simple APIs to complete. For Java, these APIs exist with java.net in this package. So just import this package and you can start network programming.
the basic model of network programming is the client-to-server model. The simple thing is that two processes communicate with each other, and then one must provide a fixed position, while the other only needs to know the fixed position. and to establish the connection between the two, and then complete the communication of the data can be. A fixed location is usually referred to as a server, and a connection is usually called a client. By understanding this simple model, you can program the network. Java supports this model in a number of APIs. And here I just want to introduce the socket programming interface, for Java has simplified the socket programming interface.
There are four constructors available for creating server-side Instances (Java provides serversocket to support them):
First, let's talk about how a service that provides a fixed location is built. In fact when you create a power object of the class and provide a port resource you build a fixed location that allows other computers to access you.
ServerSocket server=New serversocket (int port); // Port -port number, or 0, which indicates that any idle port is used.
A little note here is that the allocation of the port must be unique. Because the port is to uniquely identify each computer's unique service, and the other port number is from 0~65535, the first 1024 ports have been TCP/IP as the reserved port, so you can only allocate a port of 1024 after.
Creates a server socket bound to a specific port. Port 0 to create sockets on all idle ports. The maximum queue length for the input connection indication (Request for connection) is set to 50 . If the queue receives a connection indication when it is full, the connection is rejected.
Second, create a non-binding server.
ServerSocket server=New serversocket (); // Create a non-binding server socket
Third, create a server with the specified port, maximum number of connections.
ServerSocket server=New serversocket (int port,int//port-specified port; 0, which means that any free ports are used. Backlog-the maximum length of the queue.
Creates a server socket with the specified backlog and binds it to the specified local port number. The port number 0 creates a socket on all idle ports. The maximum queue length for the input connection indication (Request for connection) is set to backlog parameter. If the queue receives a connection indication when it is full, the connection is rejected. backlogThe parameter must be a positive value greater than 0. If the value passed is equal to or less than 0, the default value is assumed.
Four, create the specified port, maximum number of connections, specify the IP server.
ServerSocket server=New serversocket (int port,int backlog,inetaddress bindaddr); // //
Creates a server using the specified port, the listener backlog, and the local IP address to bind to. The bindaddr parameter can be used on ServerSocket's multi-homed host (multi-homed host), ServerSocket only accepts connection requests for one of its addresses. If bindaddr is null, the connection on any/all local addresses is accepted by default. The port must be between 0 and 65535, including both.
Once the server-side instance is created, you can use the thread pool to process request data from the client.
Executorservice pool = executors.newfixedthreadpool (int//poolsize fixed thread pool size
The following gives a simple structure of a network service, where the thread in the thread pool acts as an incoming request. It uses a pre-configured Executors.newFixedThreadPool(int) factory method:
Serverthread.java
Public classServerthreadextendsThread//Runnable interface can also be implemented here{ PrivateInputStream ins =NULL; PrivatePrintWriter out =NULL; PublicServerthread (socket socket) {Try{ins=Socket.getinputstream (); out=NewPrintWriter (Socket.getoutputstream (),true); Socket.setsotimeout (1000); } Catch(IOException e) {e.printstacktrace (); Interrupt (); //terminates the thread if an exception occurs } } Public voidrun () {Try { //the initialization constructor will be executed here later .//extracting data from the input stream and converting it into a string format//handle the corresponding data from the client request and do the processing .String instr = ""; inttemp =-1; List<Byte> bytelist =NewArraylist<byte>(); while(true) { Try{Temp=Ins.read (); if(Temp! =-1) {Bytelist.add (NewByte (byte) (temp)); } Else { Break; } } Catch(IOException e) { Break; } } byte[] bytes =New byte[Bytelist.size ()]; for(intI=0;i<bytelist.size (); i++) {Bytes[i]=Bytelist.get (i); } InStr=NewString (bytes);//converts a byte array type to a stringSystem.out.println ("The content of Recivedmessage is:" + instr);//This is where the message is recorded in log files.Out.println ("Request Message has been receiver!"); Out.flush (); } Catch(Exception ex) {ex.printstacktrace (); } }}View Code
Serversocketdemo.java
Public classServersocketdemoextendsthread{PrivateServerSocket Server =NULL; Private intPort = 0; Private intPoolsize = 0; Private intMaxconn = 0; PublicServersocketdemo (intPortintPoolsize,intmaxconn) {System.out.println ("Port is:>>>>>>" +port); System.out.println ("Poolsize is:>>>>>>" +poolsize); System.out.println ("Maxconn is:>>>>>>" +maxconn); This. Port =Port; This. poolsize =poolsize; This. Maxconn =Maxconn; } Public voidrun () {Try{System.out.println ("The Poolsize is:>>>>" +poolsize); System.out.println ("The Port is:>>>>" +port); System.out.println ("The Maxconn is:>>>>" +maxconn); //using a fixed-size thread poolExecutorservice Thredpool =Executors.newfixedthreadpool (poolsize); Server=NewServerSocket (port, Maxconn); Server.setsotimeout (0);//setting does not time outSYSTEM.OUT.PRINTLN ("Socket listener start!the Port is:>>>>" +Port+ "and the Maxconn number is:" +Maxconn+ "and the Thread Pool size is" +poolsize); while(true) {Thredpool.execute (NewServerthread (Server.accept ())); System.out.println ("A serverthread has been started!"); } } Catch(Exception e) {//This is where the log file is used to record the exceptionSystem.out.println ("The ServerSocket Listener exception occurred! The exception msg is>>>> "+e.getmessage ()); } }}View Code
Serversockettest.java
Public class serversockettest { /** @param args * / Public Static void Main (string[] args) { // TODO auto-generated method stub New Serversocketdemo (9997,50,100); Ssd.start (); }}
View Code
Java Socket Network Programming server