Java Socket Communication instance

Source: Internet
Author: User

I have been working on Java Web and have hardly done anything in the CS direction. I recently learned to work in Beijing and come to my place. Speaking of the written examination experience, this is probably the case with such a procedural question;

C ++ programming is used to implement a simple communication instance, requiring the server to accept messages sent from the client in real time. Although I have never done anything in this area, I also know that Java Socket is required to implement it (Frankly speaking, C ++ won't ). After work, I spent two hours writing an instance that basically met the requirements. Some problems have also been encountered, posted and learned together.

Paste the code first. Server:

Package QY. server; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import java.net. serversocket; import java.net. socket; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; public class myserver {private serversocket; // Private executorservice servicepool; // thread pool public myserver (INT port) {try {This. serversocket = new Serversocket (port); this. servicepool = executors. newfixedthreadpool (5);} catch (ioexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {New myserver (6666 ). service ();} public void Service () {int I = 0; while (true) {try {Socket socket = This. serversocket. accept (); // receives a connection and returns the socketobject named this.servicepool.exe cute (new handler (socket) of a customer. system. out. println ("user" + I + "is Connecting to the server "); I ++;} catch (ioexception e) {e. printstacktrace (); this. servicepool. shutdown () ;}} class handler implements runnable {private Socket socket; Public handler (Socket socket) {This. socket = socket ;}@ overridepublic void run () {try {// an input stream used to obtain the content from the client datainputstream Dis = new datainputstream (this. socket. getinputstream (); // The content used to generate the server's response. dataoutputstream dos = new dataoutputstr EAM (this. Socket. getoutputstream (); string STR; while (null! = (STR = dis. readutf () {system. out. println (STR); If ("exit ". equals (STR) {system. out. println ("the client sends an interrupt request"); dos. writeutf ("the server has closed this connection. "); dos. flush (); // dos. writeutf ("exit"); // dos. flush (); dos. close (); DIS. close (); break ;}} catch (ioexception e) {e. printstacktrace ();}}}}

Then, the client:

Package QY. client; import Java. io. bufferedreader; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import Java. io. inputstreamreader; import java.net. socket; public class myclient {public static void main (string [] ARGs) {try {Socket Client = new socket ("localhost", 6666); myclient me = new myclient (); new thread (Me. new handler (client )). start ();} catch (ioexception e) {e. printstacktrace () ;}} class handler implements runnable {private bufferedreader BR; private dataoutputstream DOS; private datainputstream DIS; private Socket socket; private Boolean flag = true; // used to control loop end public handler (socket s) throws ioexception {this.br = new bufferedreader (New inputstreamreader (system. in); // used to receive input information from the console, and then send it to the server this. socket = s; this. DOS = new dataoutputstream (this. socket. getoutputstream (); // output stream of data written to the server. This. dis = new datainputstream (this. socket. getinputstream (); // get the input stream of the data returned by the server} @ overridepublic void run () {While (FLAG) {try {string STR = BR. readline (); If ("exit ". equals (STR) {// The End message mark exitthis.br. close (); this. DOS. writeutf (STR); this. DOS. flush (); string res = dis. readutf (); system. out. println (RES); this. DIS. close (); this. DOS. close (); this. flag = false;} else {This. DOS. writeutf (STR); // send a row for each row read this. DOS. flush () ;}} catch (ioexception e) {e. printstacktrace ();}}}}}

Problems:

The first consideration is to use bufferedreader and bufferedwriter to write two-way data. However, it is found that bufferedwriter cannot immediately send the data obtained from the console to the server during fush, you can use the dataoutputstream data stream to complete two-way data transmission.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.