Address: http://blog.csdn.net/kongxx/article/details/7259436
Currently, there are fewer and fewer cases of using Socket directly in Java, because there are many options available, such as spring, which can support many remote connection operations, in addition, the remoting of JBoss is also a good choice, as well as Apache Mina, etc. However, in some special cases, it still cannot escape the situation of writing socket directly, such as some inexplicable game rules within the company.
If you don't talk nonsense, let's take a look at what to do if you write your own socket.
First, write a server class, which is used to listen to port 10000, receive messages from this port, and then output messages. Exit when "bye" is received.
Package COM. googlecode. garbagecan. test. socket. sample1; </P> <p> Import Java. io. bufferedreader; <br/> Import Java. io. ioexception; <br/> Import Java. io. inputstreamreader; <br/> Import Java. io. printwriter; <br/> Import java.net. serversocket; <br/> Import java.net. socket; </P> <p> public class myserver {<br/> Public static void main (string [] ARGs) throws ioexception {<br/> serversocket Server = new serversocket (10000); <br/> Socket socket = server. accept (); <br/> bufferedreader in = new bufferedreader (New inputstreamreader (socket. getinputstream (); <br/> printwriter out = new printwriter (socket. getoutputstream (); </P> <p> while (true) {<br/> string MSG = in. readline (); <br/> system. out. println (MSG); <br/> out. println ("server received" + MSG); <br/> out. flush (); <br/> If (MSG. equals ("bye") {<br/> break; <br/>}< br/> socket. close (); <br/>}< br/>}Then there is a client class, which connects to the server class started above, and then receives any user input. When a carriage return occurs, a string is sent to the server. When "bye" is input, the system exits.Package COM. googlecode. garbagecan. test. socket. sample1; </P> <p> Import Java. io. bufferedreader; <br/> Import Java. io. inputstreamreader; <br/> Import Java. io. printwriter; <br/> Import java.net. socket; </P> <p> public class myclient {<br/> Public static void main (string [] ARGs) throws exception {<br/> Socket socket = new socket ("localhost", 10000); <br/> bufferedreader in = new bufferedreader (New inputstreamreader (socket. getinputstream (); <br/> printwriter out = new printwriter (socket. getoutputstream (); <br/> bufferedreader reader = new bufferedreader (New inputstreamreader (system. in); </P> <p> while (true) {<br/> string MSG = reader. readline (); <br/> out. println (MSG); <br/> out. flush (); <br/> If (MSG. equals ("bye") {<br/> break; <br/>}< br/> system. out. println (in. readline (); <br/>}< br/> socket. close (); <br/>}< br/>}Finally, first run the myserver class, then the myclient class, and then enter any character in the myclient console. We can see that when bye is input, both the server and client will exit.