Java Socket Programming
For Java socket programming, there are two concepts, one is serversocket and the other is a socket. A connection is established between the server and the client through the socket, and then they can communicate. First ServerSocket will listen to a port on the server, when it discovers that the client has a socket to try to connect it, it will accept the connection request of the socket, and establish a corresponding socket on the server to communicate with it. So there are two sockets, the client and the server.
For the communication between the sockets is very simple, the server to the socket output stream to write something, the client can be through the socket input stream to read the corresponding content. Socket and socket are two-way connectivity, so the client can also write to the corresponding socket output stream, and then the service side of the corresponding socket input stream can read the corresponding content. Here's an example of server-to-client communication:
multiple clients connect to the same servereveryServerSocketreceive a newSocketafter the connection request, a new thread is started to follow the currentSocketso that asynchronous processing is achieved with the clientSocketthe situation in which communication occurs. we use BufferedReader to read one line at a time, not how many bytes are read at a time
Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.reader;import Java.io.writer;import Java.net.ServerSocket;import Java.net.socket;public class Server {public static void main (String args[]) throws IOException {//For the sake of simplicity, all exception information all outward int port = 8899; Define a ServerSocket listener on port 8899 serversocket server = new ServerSocket (port); while (true) {//server attempts to receive connection requests from other sockets, the server's accept method is a blocked socket socket = server.accept (); A new thread is created for each socket that is received to process it. Start (); }}/** * * * Static class Task implements Runnable {Private socket socket for processing Socket request; Public Task (socket socket) {this.socket = socket; } public void Run () {try {handlesocket (); } catch (Exception e) {e.printstacktrace (); } } /*** Communication with Client socket * @throws Exception */private void Handlesocket () throws Exception {Bufferedrea Der br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); StringBuilder sb = new StringBuilder (); String temp; int index; while ((Temp=br.readline ()) = null) {System.out.println (temp); if (index = Temp.indexof ("EOF"))! =-1) {//when encountering EOF, end receiving Sb.append (temp.substring (0, index)); Break } sb.append (temp); } System.out.println ("From client:" + SB); After reading, write a writer writer = new OutputStreamWriter (Socket.getoutputstream ()); Writer.write ("Hello Client."); Writer.write ("eof\n"); Writer.flush (); Writer.close (); Br.close (); Socket.close (); } }}
this time, it's important to note thatBufferedReaderof theReadLinemethod is to read one line at a time, this method is blocked until it reads a line of data so that the program continues to execute .ReadLinewhen do you read a line? until the program encounters a newline character or a terminator of the corresponding stream ReadLinemethod is considered to have read a line before it ends its blocking, so the program continues to execute down. So we are usingBufferedReaderof theReadLinewhen reading data, be sure to write a newline character in the corresponding output stream (the end of the stream is automatically marked as the end,ReadLinecan be recognized), after writing a newline character remember that if the output stream is not closed immediatelyFlushso that the data is actually written from the buffer. corresponding to the above code, our client program should write this:
Client:
Assuming that there is a requirement, our client needs to obtain the XX information from the server through the socket and then present it to the user on the page. We know that the socket is blocked when reading the data, and if it is not read, the program will always block there. We must not allow this to happen when synchronizing requests, which requires us to control blocking interrupts after the request has reached a certain time, allowing the program to continue running. The socket provides us with a setsotimeout () method to set the time-out for receiving data in milliseconds. When the timeout period is greater than 0, and the socket has not received the returned data, the socket will throw a sockettimeoutexception.
Let's say we need to control how our clients interrupt blocking if they haven't read the data for 10 seconds before they start reading the data, we can do this:
Import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.writer;import Java.net.socket;import Java.net.sockettimeoutexception;public class Client {public static void M Ain (String args[]) throws Exception {//For the sake of simplicity, all exceptions are thrown directly out of String host = "127.0.0.1"; The server-side IP address to connect int port = 8899; The listener port corresponding to the server to be connected//connect with the server socket client = new socket (host, port); After the connection is established, the data can be written to the server. Writer writer = new OutputStreamWriter (Client.getoutputstream ()); Writer.write ("Hello Server."); Writer.write ("eof\n"); Writer.flush (); After writing, read operations BufferedReader br = new BufferedReader (New InputStreamReader (Client.getinputstream ())); Set the timeout time to 10 seconds client.setsotimeout (10*1000); StringBuffer sb = new StringBuffer (); String temp; int index; try {while ((Temp=br.readline ()) = null) {if (index = Temp.indexof ("EOF"))! =-1) { Sb.append (Temp.substriNg (0, index)); Break } sb.append (temp); }} catch (Sockettimeoutexception e) {System.out.println ("data read timeout. "); } System.out.println ("From server:" + SB); Writer.close (); Br.close (); Client.close (); }}
Really thank you for writing this article blogger, reproduced from http://haohaoxuexi.iteye.com/blog/1979837 can see the original text more detailed understanding
Java Socket Programming