In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to solve the blocking problem of socket using getInputStream () in Java". In daily operation, I believe that many people have doubts about how to solve the blocking problem of socket using getInputStream () in Java. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to solve the blocking problem of socket using getInputStream () in Java". Next, please follow the editor to study!
Socket uses getInputStream () blocking
Today, when I was doing programming exercises with socket, I found that the program couldn't go on when it came to getInputStream ().
Socket socket = new Socket (127.0.0.1); ObjectInputStream reader = new ObjectInputStream (socket.getInputStream ()); System.out.println ("a"); ObjectOutputStream writer = new ObjectOutputStream (socket.getOutputStream ())
With such a test code, a will not print out.
It turns out that getInputStream () will block there all the time.
I just adjusted two lines of code. I don't know why. Write it down first.
Socket socket = new Socket ("127.0.0.1", 800); ObjectOutputStream writer = new ObjectOutputStream (socket.getOutputStream ()); System.out.println ("a"); ObjectInputStream reader = new ObjectInputStream (socket.getInputStream ()); solve getInputStream blocking of Socket with threads 1. Background
In Socket communication, when we want to transfer objects, we often use the input / output object stream.
ObjectInputStream in=new ObjectInputStream (socket.getInputStream ()); ObjectOutputStream out=new ObjectOutputStream (socket.getOutputStream ()); 2. problem
When the program calls socket.getInputStream () the program is stuck.
3. Reason
The socket.getInputStream () method causes the program to block until inputStream receives a message from the other side before the program continues to execute.
The official API of public ObjectInputStream (InputStream in) throws IOException shows:
Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header. [1]
4. Solution.
Handle the input stream in a threaded manner. The following is the sample code:
/ / = client code SocketClient.java=
Import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.net.Socket;import java.net.UnknownHostException; public class SocketClient {private Socket socket; private ObjectOutputStream out; private ObjectInputStream in; public SocketClient () {try {socket=new Socket ("localhost", 8081); out=new ObjectOutputStream (socket.getOutputStream ()) ReadThread readThread=new ReadThread (); readThread.start ();} catch (UnknownHostException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace () }} public void sendMessage (String msg) {System.out.println ("send message:" + msg); try {out.writeObject (msg); out.flush () } catch (IOException e) {e.printStackTrace ();}} class ReadThread extends Thread {boolean runFlag=true; public void run () {try {in=new ObjectInputStream (socket.getInputStream ()) } catch (IOException E1) {e1.printStackTrace ();} while (runFlag) {if (socket.isClosed ()) {return } try {Object obj=in.readObject (); if (obj instanceof String) {System.out.println ("Client recive:" + obj) }} catch (IOException e) {e.printStackTrace () } catch (ClassNotFoundException e) {e.printStackTrace () } public void exit () {runFlag=false;}} public static void main (String [] args) {SocketClient socketClient=new SocketClient () System.out.println ("build socketClient"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} socketClient.sendMessage ("Hello first.") Try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} socketClient.sendMessage ("Hello second.");}}
/ / = server-side code SocketService.java=
Import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketException;import java.util.Date; public class SocketService {ServerSocket serverSocket; public SocketService () {try {serverSocket=new ServerSocket (8081) While (true) {Socket socket=serverSocket.accept (); SocketServiceThread sst=new SocketServiceThread (socket); sst.start ();} catch (IOException e) {e.printStackTrace () }} class SocketServiceThread extends Thread {Socket socket; ObjectInputStream in; ObjectOutputStream out; boolean runFlag=true; public SocketServiceThread (Socket socket) {if (null==socket) {runFlag=false Return;} this.socket=socket; try {out=new ObjectOutputStream (socket.getOutputStream ());} catch (IOException e) {e.printStackTrace () }} public void run () {if (null==socket) {System.out.println ("socket is null"); return } try {in=new ObjectInputStream (socket.getInputStream ()) While (runFlag) {if (socket.isClosed ()) {System.out.println ("socket is closed"); return } try {String obj= (String) in.readObject () If (obj instanceof String) {System.out.println ("Server recive:" + obj); Date date=new Date () Out.writeObject ("[" + date+ "]" + obj); out.flush () } else {System.out.println ("Server recive:" + obj) }} catch (ClassNotFoundException e) {e.printStackTrace () } catch (SocketException e) {e.printStackTrace (); return } catch (IOException e) {e.printStackTrace () } catch (IOException E1) {e1.printStackTrace (); return } catch (Exception e) {return;}} public void exit () {runFlag=false }} public static void main (String [] args) {System.out.println ("= start service="); new SocketService ();}} 5.Socket communication considerations
(1). The writeXXX () method is usually followed by flush () to send out the cached content.
(2)。 When sending an object, the object must be serialized, that is, the object needs to implement the Serializable interface.
At this point, the study on "how to solve the blocking problem of socket using getInputStream () in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.