Methods for using socket communication for multithreading and long connections in Java Web projects _java

Source: Internet
Author: User
Tags readline thread class java web

A lot of times in the Javaweb project we need to use socket communication to achieve functionality, the use of sockets in the web we need to establish a listener, when the program is started, the socket listening. Our scenario is in a Java project that needs to be external such as a hardware device, through TCP communication, get the data from the device, and respond to the data.

Take a look at the web's listening code first:

Import javax.servlet.ServletContextEvent;
Import Javax.servlet.ServletContextListener;
public class Attendsocetlistener implements servletcontextlistener{
private socketthread socketthread;
public void contextdestroyed (Servletcontextevent arg) { 
if Null!=socketthread &&! Socketthread.isinterrupted ()) 
{ 
socketthread.closesocketserver (); 
Socketthread.interrupt (); 
} 
@Override public 
void contextinitialized (servletcontextevent arg) { 
//TODO auto-generated method stub 
if (Null==socketthread) 
{ 
//New Thread class 
socketthread=new socketthread (null); 
Start thread 
socketthread.start ();}} 

To create a thread:

Import java.io.IOException;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.util.ArrayList;
Import java.util.List; 
public class Socketthread extends Thread {private ServerSocket serversocket = null;  
Public Socketthread (ServerSocket serverscoket) {try {if (null = = ServerSocket) {this.serversocket = new ServerSocket (); 
SYSTEM.OUT.PRINTLN ("socket start"); 
The catch (Exception e) {System.out.println ("Socketthread Create socket Service error"); 
E.printstacktrace (); } public void Run () {while (true) {try {if (serversocket==null) {break;}
else if (serversocket.isclosed ()) {break;} 
Socket socket = serversocket.accept (); 
if (null!= socket &&!socket.isclosed ()) {//process accepted data thread t = new Thread (new Socketoperate (socket)); 
T.start (); }else{break;} 
catch (Exception e) {System.out.println ("Socketthread Create socket Service error"); 
E.printstacktrace (); }} public void Closesocketserver () {try {if (Null!=serversocket &&!serversocket.isclosed ()) {SERVERSOCKet.close (); 
The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } 
} 
}

Processing received data:

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.net.Socket; 
public class Socketoperate implements Runnable {private socket socket; 
The input stream for the socket processed by the thread bufferedreader br = NULL; 
String str = NULL; 
String content = null; 
InputStreamReader Reader=null; 
Public socketoperate (socket socket) throws IOException {this.socket = socket; 
reader = new InputStreamReader (This.socket.getInputStream (), "utf-"); 
br = new BufferedReader (reader); 
@Override public void Run () {try {///loops through the socket to read the data sent by the client while (true) {content = Readfromclient ();
SYSTEM.OUT.PRINTLN (content); 
if (content = = null) {break; 
} outputstream OS = Socket.getoutputstream (); 
Os.write ("RES, ok,<, Xiaoming,,, #" + "\ n"). GetBytes ("utf-"));
Os.flush (); 
} catch (IOException e) {e.printstacktrace (); 
}//define methods to read client data private String readfromclient () {try {str = br.readline (); 
return str; }
If an exception is caught, the client that corresponds to the socket has closed catch (IOException e) {try {br.close (); Reader.close (); Socket.close ();} catch (Ioexc 
Eption e) {//TODO auto-generated catch block E.printstacktrace ();} 
return null; } 
}

Client code:

Package
import java.io.*;
Import java.net.*;
public class Talkclient {public
static void Main (String args[]) throws Unknownhostexception, IOException {
Socke T socket=new socket ("...",);
PrintWriter os=new PrintWriter (Socket.getoutputstream ());
BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
int i=;
while (socket.isconnected ()) {
os.print ("BEAT,,,,.,, #" + "\ n");
Os.flush ();
System.out.println ("Client:" +i);
System.out.println ("Server:" +is.readline ());
i++;
} 
Continue cycle
os.close ();///close socket output stream
is.close ();//close socket input stream
socket.close ();//close socket
}
}

The above is a small series to introduce the Java Web project in the use of socket communication multithreading, long connection method, I hope to help!

Related Article

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.