In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 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 multithreaded communication based on Socket, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.
Code introduction
Code ideas:
Two problems need to be solved to realize the communication between "server-client".
(1) how to realize communication
(2), how to avoid the problem of single thread receiving before sending (or sending before receiving) in communication.
Solution:
(1) to achieve communication: after using ServerSocket to listen on the designated port, the Socket connects; then both the client and the server obtain the input and output streams of the Socket object and store them in PrintWrite to achieve communication.
(2) to make up for the defect of single thread: create message receiving class and message sending class inheriting Thread; respectively, and then avoid the problem that single thread must receive before sending (or sending before receiving) by opening two threads.
Server side
Package x_Socket
Import java.io.BufferedReader
Import java.io.IOException
Import java.io.InputStreamReader
Import java.io.PrintWriter
Import java.net.ServerSocket
Import java.net.Socket
Public class x_Server {
/ * * declare global objects so that the inner classes of x_Server can call them together * * /
Static ServerSocket serverSocket = null;// declares a static global socket class object; allows static methods of x_Server to call the object directly
Static Socket socket = null; / / declare a static global socket class object; let the static method of x_Server call the object directly
BufferedReader buffSend = null; / / Information sending data stream
BufferedReader buffReciever = null; / / Information receive data stream
PrintWriter printWriter = null; / / data read / write data stream
/ * * main function entry * * /
Public static void main (String [] args) throws IOException {
ServerSocket = new ServerSocket (5556); / / through the constructor of Socket, the listening port 5556 (that is, waiting for the socket object to request a connection to this port)
Socket = serverSocket.accept (); / / if an object request of socket connects to port 5556, the accept of serverSocket returns a socket object
System.out.println ("A user successfully connected to the client")
Thread xsend = new Thread (new x_Server (). New x_Send ()); / / create a thread object of the x_Send class through the constructor of the Thread class
Thread xreciver = new Thread (new x_Server (). New x_Receiver ()); / / the inner class is instantiated through the external class object, and then the thread two objects of the inner class x_Reciever are created through the constructor of Thread.
Xsend.start (); / / starts the thread of x_Send so that sending and receiving data can be done at the same time
Xreciver.start (); / / starts the thread of x_Receiver so that sending and receiving data can be done at the same time
}
/ * * x_Send class for sending messages on the server (thread 1) * * /
Class x_Send extends Thread {
Public void run () {/ / inherits the Thread class and must override the run () method
Try {
BuffSend = new BufferedReader (new InputStreamReader (System.in)); / / get the object buffSend that inputs data from the console
PrintWriter = new PrintWriter (socket.getOutputStream ()); / / obtain the output stream object that sends information to the client through the constructor of the PrintWriter class
String msg = null; / / msg: stores the information sent by the server
Do {
Msg = buffSend.readLine (); / / get the information to enter a line from the console
PrintWriter.println (msg); / / transfer the msg to the output stream object that sends information to the server
PrintWriter.flush (); / / refresh the input and output stream, and the client can receive the update information of the input and output stream immediately.
} while (! msg.equals ("end")); / / customer enters "end" to end communication
Socket.close (); / / close the connection to port 5556
ServerSocket.close (); / / no longer listens on port 5556 (that is, no longer receives connections from that port)
} catch (IOException e) {
System.out.println (client connection disconnected)
E.printStackTrace ()
}
}
}
/ * * x_Reciever class (thread 2) used for server to receive information * * /
Class x_Receiver extends Thread {
Public void run () {/ / inherits the Thread class and must override the run () method
Try {
BuffReciever = new BufferedReader (new InputStreamReader (socket.getInputStream (); / / gets the input stream object that inputs data from socket (transferred from the client)
While (true) {
System.out.println ("receive client message:" + buffReciever.readLine ()); / / output the information transmitted by the client
}
} catch (IOException e) {
System.out.println ("client connection disconnected:\ n")
E.printStackTrace ()
}
}
}
}
Client
Package x_Socket
Import java.io.BufferedReader
Import java.io.IOException
Import java.io.InputStreamReader
Import java.io.PrintWriter
Import java.net.Socket
Import java.net.UnknownHostException
Public class x_Client {
/ * * declare global objects so that the inner classes of x_Client can call them together * * /
Static Socket socket = null; / / declare a static global socket class object; let the static method of x_Client call the object directly
BufferedReader buffSend = null; / / Information sending data stream
BufferedReader buffReciever = null; / / Information receive data stream
PrintWriter printWriter = null; / / data read / write data stream
/ * * main function entry * * /
Public static void main (String [] args) throws UnknownHostException, IOException {
Socket = new Socket ("127.0.0.1", 5556); / / connect port 5556 of the local ip through the constructor of Socket
System.out.println ("connection server information is as follows:\ nip:127,0.0.1 port:5556")
Thread xsend = new Thread (new x_Client (). New x_SendMsg ()); / / create a thread object of the x_SendMsg class through the constructor of the Thread class
Thread xreciver = new Thread (new x_Client (). New x_RecieverMsg ()); / / the inner class is instantiated through the external class object, and then the thread two objects of the inner class x_RecieverMsg are created through the constructor of Thread.
Xsend.start (); / / the thread that starts x_SendMsg
Xreciver.start (); / / starts the x_RecieverMsg thread; two allow sending and receiving data to occur at the same time
}
/ * * x_SendMsg class for sending messages from the client (thread 1) * * /
Class x_SendMsg extends Thread {
Public void run () {/ / inherits the Thread class and must override the run () method
Try {
BuffSend = new BufferedReader (new InputStreamReader (System.in)); / / get the object buffSend that inputs data from the console
PrintWriter = new PrintWriter (socket.getOutputStream ()); / / obtain the output stream object that sends information to the server through the constructor of the PrintWriter class
String msg = null; / / msg: stores the information sent by the client
Do {
Msg = buffSend.readLine (); / / get the information to enter a line from the console
PrintWriter.println (msg); / / transfer the msg to the output stream object that sends information to the server
PrintWriter.flush (); / / refresh the input and output stream, and the server can receive the update information of the input and output stream immediately.
} while (! msg.equals ("end")); / / customer enters "end" to end communication
Socket.close (); / / close the connection to port 5556
} catch (IOException e) {
System.out.println ("server port is closed"); / / exception message display
E.printStackTrace (); which is a good http://www.zykeda120.com/ for Zhengzhou fetus expelling Hospital?
}
}
}
/ * x_RecieverMsg class for the client to receive information (thread 2) * * /
Class x_RecieverMsg extends Thread {
Public void run () {/ / inherits the Thread class and must override the run () method
Try {
BuffReciever = new BufferedReader (new InputStreamReader (socket.getInputStream (); / / gets the input stream object of the data input from the socket (transmitted from the server)
While (true) {
System.out.println ("receive server message:" + buffReciever.readLine ()); / / output the information transmitted by the server
}
} catch (IOException e) {
System.out.println ("server port is closed"); / / exception message display
E.printStackTrace ()
}
}
Thank you for reading this article carefully. I hope the article "how to achieve multithreaded communication based on Socket 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.