?? This address: http://blog.csdn.net/kongxx/article/details/7259436
Now the use of Java directly using the socket is less, because there are many options, such as spring can be used, which can support a wide range of remote connection operations, and JBoss Remoting is also a good choice, as well as Apache Mina and so on, However, in some cases, some special circumstances can not escape the direct write socket, such as the company's internal some inexplicable rules of the game.
If you don't talk about it, let's see what you can do if you write your own socket.
The first is to write a server class that listens on port 10000 and receives a message from this port and outputs it when it receives "bye".
[Java] view Plaincopyprint?
Package Com.googlecode.garbagecan.test.socket.sample1;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 MyServer {public static void main (string[] args) throws IOException {ServerSocket server = new ServerSocket (1 0000); Socket socket = server.accept (); BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); PrintWriter out = new PrintWriter (Socket.getoutputstream ()), while (true) {String msg = In.readline (); SYSTEM.OUT.PRINTLN (msg); Out.println ("Server received" + msg); Out.flush (); if (Msg.equals ("Bye")) {break;}} Socket.close ();}}
Then there is a client class, this class connects the server class that is started above, and then receives any user input when it encounters a carriage return when it sends the string to the server, when the input "Bye" is exited.
[Java] view Plaincopyprint?
Package Com.googlecode.garbagecan.test.socket.sample1;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.io.printwriter;import Java.net.socket;public class MyClient {public static void Main (string[] args) throws Exception {socket socket = new socket ("localhost", 10000); BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); PrintWriter out = new PrintWriter (Socket.getoutputstream ()); BufferedReader reader = new BufferedReader (new InputStreamReader (system.in)); while (true) {String msg = Reader.readline ( ); Out.println (msg); Out.flush (); if (Msg.equals ("Bye") {break;} System.out.println (In.readline ());} Socket.close ();}}
Finally, run the MyServer class first, then myclient the class, and then enter any characters in the MyClient console, and you can see that when the input bye is both server and client exit.
One of the Java socket real-time single thread communication