The Java API provides a server socket ServerSocket class and a client socket for our network communication Socket,socket is the interface and mechanism that the network driver provides to the application programming. Here is a concrete example of implementation Service-side--serversocketThe ServerSocket class implements the socket of the server, the Main methodserversocket (int port)-----Create a server socket bound to a specific portvoid Setsotimeout (timeout);----Specify a time-outinetadress getinetaddress ()----Returns the native address of this server socketsocket Accept ()--------------listen and accept connections for this socket Example code:
- Package com;
- Import Java.io.BufferedInputStream;
- Import Java.io.BufferedOutputStream;
- Import java.io.IOException;
- Import Java.net.ServerSocket;
- Import Java.net.Socket;
- public class Test {
- public static void Main (string[] args) {
- try {
- ServerSocket server=new serversocket (8080);
- Waiting for client connections
- while (true) {
- Socket client=server.accept ();
- Each client builds a thread
- New Thread (new myrunnable (client)). Start ();;
- }
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
- Class Myrunnable implements runnable{
- private socket socket;
- Public myrunnable (Socket s)
- {
- This.socket=s;
- }
- ----Run method is complete, thread ends normally
- @Override
- public void Run () {
- try {
- Receiving client data
- Bufferedinputstream is=new Bufferedinputstream (Socket.getinputstream ());
- int Data=is.read () +1;//Add a customer's data
- Thread.Sleep (1000);//sleep for one second
- Output to Client
- Bufferedoutputstream os=new Bufferedoutputstream (Socket.getoutputstream ());
- Os.write (data);//return to the client
- Os.close ();
- Os.close ();
- } catch (IOException | Interruptedexception e) {
- E.printstacktrace ();
- }
- }
- }
Copy CodeClient----SocketThe socket class implements the client socket, which is the endpoint of the communication between the two machines, and the main method is socket (String host,int port)----Create a socket to connect it to the specified port number for the specified hostInputStream getinputstream ()----returns the input stream for this socketoutputstream getoutputstream ()----returns the output stream for this socket Example code:
- Package com;
- Import Java.io.BufferedInputStream;
- Import Java.io.BufferedOutputStream;
- Import java.io.IOException;
- Import Java.net.Socket;
- Import java.net.UnknownHostException;
- public class Client {
- public static void Main (string[] args) {
- for (int i=0;i<20;i++)
- {
- try {
- Socket socket = new socket ("localhost", 8080);
- Output to Server
- Bufferedoutputstream os=new Bufferedoutputstream (Socket.getoutputstream ());
- Os.write (i);
- Os.flush ();
- Os.close (); no more closing the stream here, closing the stream will cause the socket to also close
- Building character Buffer streams
- Bufferedinputstream is=new Bufferedinputstream (Socket.getinputstream ());
- int Data=is.read ();
- Is.close ();
- Os.close ();
- SYSTEM.OUT.PRINTLN (data);
- } catch (Unknownhostexception e) {
- E.printstacktrace ();
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
- }
Copy CodePrimary cannot close the input and output stream prematurely, closing the input/output stream will cause the socket to close
There are 4 things that can cause network connections to close: 1. Call the Close method of the socket class directly. 2. As long as the socket class InputStream and OutputStream have a shutdown, the network connection automatically shuts down (you must close the stream by calling the Close method of InputStream and OutputStream to make the network cute to shut down automatically). 3. The network connection shuts down automatically when the program exits. 4. Set the socket object to null or not close the most used new socket (...) After a new object is created, the network connection is automatically closed after the JVM's garbage collector reclaims the memory allocated by the socket object. thread Poolwhen working with multiple clients, one thread is created for each connection, but frequent thread creation affects performance, so we can use the thread pool to solve the problem of creating frequent threads. Thread pool: A thread pool is a technique for pre-creating threads. The thread pool creates a certain number of threads before the task arrives, places them in the idle queue, and then re-uses them to reduce frequent thread creation and destruction. The thread pool is provided after the JDK1.5 version, the top interface of the thread pool is executor, is an execution tool, and the direct interface of the thread pool is executorservice, which is a common tool class in concurrent development to configure a thread pool is more complex, especially if the thread pool principle is not very clear, it is likely that the thread pool configured is not superior, so there are some static factories in the executors class that generate some common thread pools. 1. Newsinglethreadexecutor creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted. 2. Newfixedthreadpool creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception. 3. Newcachedthreadpool creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task, then a partially idle (60 second non-performing) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create. 4. NewscheduledthreadpoolCreate a thread pool of unlimited size. This thread pool supports the need to schedule and periodically perform tasks. At this point we are on the server with the online pool, using Newfixedthreadpool, the code is changed to Java code [Url=][/url]
- Package com;
- Import Java.io.BufferedInputStream;
- Import Java.io.BufferedOutputStream;
- Import java.io.IOException;
- Import Java.net.ServerSocket;
- Import Java.net.Socket;
- Import Java.util.concurrent.ExecutorService;
- Import java.util.concurrent.Executors;
- public class Test {
- public static void Main (string[] args) {
- try {
- ServerSocket server=new serversocket (8080);
- Get the number of CPUs
- int Cpu_num=runtime.getruntime (). Availableprocessors ();
- Create a thread pool of the specified size
- Executorservice Es=executors.newfixedthreadpool (Cpu_num);
- Waiting for client connections
- while (true) {
- Socket client=server.accept ();
- Each client builds a thread
- New Thread (new myrunnable (client)). Start ();
- Es.execute (new myrunnable (client));
- }
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
- Class Myrunnable implements runnable{
- private socket socket;
- Public myrunnable (Socket s)
- {
- This.socket=s;
- }
- ----Run method is complete, thread ends normally
- @Override
- public void Run () {
- try {
- Receiving client data
- Bufferedinputstream is=new Bufferedinputstream (Socket.getinputstream ());
- int Data=is.read () +1;//Add a customer's data
- Thread.Sleep (1000);//sleep for one second
- Output to Client
- Bufferedoutputstream os=new Bufferedoutputstream (Socket.getoutputstream ());
- Os.write (data);//return to the client
- Os.close ();
- Os.close ();
- } catch (IOException | Interruptedexception e) {
- E.printstacktrace ();
- }
- }
- }
Copy CodeThis is true although the concurrent server, but such a low efficiency server, low throughput, want to improve server performance, you can study Java NIO and AIO, can greatly improve server performance. |