In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces java how to achieve socket connection method encapsulation, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Skills of implementing socket connection with Java
Socket communication is almost all the time, of course, there is a lot of information that can be collected. In order to avoid repeated work, we extract the Socket about the client and server, and apply it to the JVM (LInux/Windows) or DVM (Android) platform.
This encapsulated API has the following advantages:
1. Meet the basic applications with Socket client requirements.
two。 Meet the basic application with Socket server. It has the concurrency ability and can meet the number of client connections that can be set.
The purpose of this paper is to encapsulate Socket so that clients and servers can directly use Socket. Packaged API can be obtained from the following
Encapsulation of Java Socket
Among them, src/ is the API source code; usage/ directory is the use of routines
1 key points of client Socket API
1) the client is connected to the specified server, so the client needs to specify the IP address and port number corresponding to the server.
2) timeout return needs to be set.
3) Loop wait needs to be set, because basic Socket communication is done back and forth, and this round trip is done through blocking.
4) when each client connects to the server, it has its own ID, which is similar to HTTP's Session, which is easy to be ignored. In multi-client connections, you can focus on. The code provided in this article is also mentioned, but not in depth, which is left to the reader to explore further.
The code refers to the client test code in the / usage directory. Note that it is good to start the server first, or you can test it with NetAssis.
2 main points of server Socket API
1) the server is generally connected by multiple clients, and these connections require the server to do similar processing, so here the similar processing is abstracted into a SingleTask.java interface, and the specific business only needs to implement such an interface to process these Task in parallel.
2) clients cannot be connected to Server indefinitely, so you need to set an upper limit
3) start the thread pool, each thread for a specific client connection
4) pay attention to the receiving blocking position, you need to set a dead loop, and if you can't read the data, you will be waiting (but don't delay other threads from handling things).
5) pay attention to the server listening in an endless loop to ensure that no requests from the client are missed.
The code refers to the server-side test code under the / usage directory.
There are a lot of comments in the code, so I won't go into detail here.
common problem
1. If there is a network problem in the client Client, in order to avoid the network problem and cause the client to wait for a long time, set a TimeOut at this time
ClientSocket = new Socket (); / / this TimeOut is the connection latency clientSocket.connect (tcpAddress, timeOut)
2. When the client has connected and receives a data each time, the client will start processing. If the server does not send data for a long time, the client will block waiting. In order to avoid waiting at this time, you can set a timeout.
ClientSocket.setSoTimeout (timeOut); Java uses socket to implement a multithreaded web server. In addition to server classes, request classes and response classes are also included.
Request class: get the customer's HTTP request, analyze the file response class that the customer needs: after obtaining the user's request, read out the file needed by the user, and add the HTTP response header. Send it to the client.
Server processing class package com.lp.app.webserver;import java.io.*;import java.net.*;// uses Socket to create a WEB server, this program is a multi-threaded system to improve response speed. Class WebServer {public static String WEBROOT = ""; / / default directory public static String defaultPage = "index.htm"; / / default file public static void main (String [] args) throws IOException {System.out.println ("server startup.\ n"); / / provide services using port 8080 ServerSocket server = new ServerSocket (8080); while (true) {/ / blocking until a customer connects Socket sk = server.accept () System.out.println ("Accepting Connection...\ n"); / / start the service thread new WebThread (sk). Start ();} / / use threads to serve multiple clients class WebThread extends Thread {private Socket sk; WebThread (Socket sk) {this.sk = sk;} / / thread body public void run () {InputStream in = null; OutputStream out = null; try {in = sk.getInputStream (); out = sk.getOutputStream () / / receive a request from the client. Request rq = new Request (in); / / resolve customer request String sURL= rq.parse (); System.out.println ("sURL=" + sURL); if (sURL.equals ("/")) sURL= WebServer.defaultPage; Response rp = new Response (out); rp.Send (sURL);} catch (IOException e) {System.out.println (e.toString ());} finally {System.out.println ("close connection.\ n") / / finally release the resources try {if (in! = null) in.close (); if (out! = null) out.close (); if (sk! = null) sk.close ();} catch (IOException e) {} request class package com.lp.app.webserver;import java.io.*;import java.net.*;// to obtain the customer's HTTP request, and analyze the file public class Request {InputStream in = null needed by the customer / / get the input stream. This is the customer's request data. Public Request (InputStream input) {this.in = input;} / / parse the customer's request public String parse () {/ / read a set of data from Socket StringBuffer requestStr = new StringBuffer (2048); int i; byte [] buffer = new byte [2048]; try {I = in.read (buffer);} catch (IOException e) {e.printStackTrace (); I =-1;} for (int jung0; j index1) return requestString.substring (index1 + 1, index2);} return null }} the response class package com.lp.app.webserver;import java.io.*;import java.net.*;// reads out the files needed by the user after obtaining the user's request, and adds the HTTP response header. Send it to the client. Public class Response {OutputStream out = null; / / send the requested file public void Send (String ref) throws IOException {byte [] bytes = new byte [2048]; FileInputStream fis = null; try {/ / Construction file File file = new File (WebServer.WEBROOT, ref); if (file.exists ()) {/ / construct the input file stream fis = new FileInputStream (file); int ch = fis.read (bytes,0, 2048); / / read the file String sBody = new String (bytes,0) / / Construction output information String sendMessage = "HTTP/1.1 200 OK\ r\ n" + "Content-Type: text/html\ r\ n" + "Content-Length:" + ch+ "\ r\ n" + "\ r\ n" + sBody; / / output file out.write (sendMessage.getBytes ()) } else {/ / cannot find the file String errorMessage = "HTTP/1.1 404 File Not Found\ r\ n" + "Content-Type: text/html\ r\ n" + "Content-Length: 23\ r\ n" + "\ r\ n" + "File Not Found"; out.write (errorMessage.getBytes ());}} catch (Exception e) {/ / if the File object cannot be instantiated, throw an exception. System.out.println (e.toString ());} finally {if (fis! = null) fis.close ();}} / / get output stream public Response (OutputStream output) {this.out = output }} Thank you for reading this article carefully. I hope the article "how to achieve socket connection method encapsulation in java" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.