Socket (Java) simple communication between multiple clients and servers (multithreading)

Source: Internet
Author: User
Original works can be reprinted. During reprinting, you must mark the original source, author information, and this statement in hyperlink form. Otherwise, legal liability will be held. Http://blog.csdn.net/love254443233/article/details/7897269


Implementation:

Client: Multiple Sockets (multiple ports). One of the client's ports is used to receive messages sent from the server, and the other is used to send messages to the server. Other clients only have the message sending function.

Server: two sockets, one used to receive socket requests sent by the client cyclically. One receiver automatically sends messages to the client.

Note:Run mysocketserver first, then mysocketclient, and then socketclient; mysocketclient and socketclient send messages to mysocketserver.

1. mysocketserver class:

Package socket. _ 5; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import java.net. serversocket; import java.net. socket; public class mysocketserver {Private Static int localhostport = 5000; public static void main (string [] ARGs) throws ioexception {serversocket S = new serversocket (localhostport); system. out. println ("server ------ listening ..... "); While (true) {Socket socket = s. Accept (); system. out. println ("connected socket:" + socket); getmessage = new getmessage (socket); thread = new thread (getmessage); thread. start () ;}}// class getmessage implements runnable {private int remoteport = 5001; private string remoetaddress = "localhost"; private inputstream; private outputstream; private socket socketget; private socket socketsendmessage; PR Ivate Boolean socketisexits = false; private int sum = 0; private byte [] buffer; Public getmessage (Socket socket) {This. socketget = socket; try {inputstream = socketget. getinputstream (); outputstream = socketget. getoutputstream ();} catch (ioexception e) {e. printstacktrace () ;}} public void run () {string STR = ""; int n = 0; while (true) {try {buffer = new byte [2048]; N = inputstream. read (buffer); STR = new S Tring (buffer, 0, n); system. out. print ("client:" + Str); sendmessage ();} catch (ioexception e) {e. printstacktrace (); break;} If (Str. equals ("Q") {break;} Try {If (socketget! = NULL) socketget. Close (); If (inputstream! = NULL) inputstream. close ();} catch (exception e) {}} // send the message public void sendmessage () throws ioexception {If (socketisexits) {try {string input = "====" + (sum ++); system. out. println ("socket sent by the server:" + this. socketsendmessage); outputstream. write (input. getbytes (); system. out. println ("server:" + input); outputstream. flush ();} catch (exception e) {system. out. println ("the client socket does not exist. "); Checksocket () ;}} else {checksocket () ;}} private void checksocket () {try {socketsendmessage = new socket (remoetaddress, remoteport); outputstream = socketsendmessage. getoutputstream (); socketisexits = true;} catch (exception e) {socketisexits = false ;}}}

2. mysocketclient class:

Package socket. _ 5; import Java. io. *; import java.net. *; public class mysocketclient {Private Static int localhostport = 5001; public static void main (string [] ARGs) throws ioexception {csendmessage = new csendmessage (); thread thread2 = new thread (csendmessage); thread2.start (); serversocket = new serversocket (localhostport); While (true) {socket socketserver = serversocket. accept (); Cgetmessage getmessage = new cgetmessage (socketserver); thread = new thread (getmessage); thread. start () ;}}// receives the message class cgetmessage implements runnable {private inputstream; private socket; private byte [] buffer; Public cgetmessage (Socket socket) {This. socket = socket; try {inputstream = socket. getinputstream ();} catch (ioexception e) {e. printstacktrace () ;}} public void run () {String STR = ""; while (true) {buffer = new byte [2048]; int n = 0; try {n = inputstream. read (buffer); STR = new string (buffer, 0, n); system. out. println ("server:" + Str);} catch (ioexception e) {e. printstacktrace (); break;} If (Str. equals ("Q") {break;} Try {If (socket! = NULL) socket. Close (); If (inputstream! = NULL) inputstream. close () ;}catch (exception e) {}}// sends the class csendmessage implements runnable {private Boolean socketisexits = false; private outputstream; private socket socketclient; private int remoteport = 5000; private string remoteaddress = "localhost"; private byte [] buffer; Public csendmessage () throws ioexception {} public void run () {string STR = new string (); checksocket (); int Size = 0; while (true) {try {system. out. println ("Enter:"); buffer = new byte [2048]; size = system. in. read (buffer); STR = new string (buffer, 0, size);} catch (ioexception e) {e. printstacktrace ();} If (socketisexits) {try {system. out. println ("client sends socket:" + this. socketclient); system. out. print ("client:" + Str); outputstream. write (Str. getbytes (); outputstream. flush ();} catch (exception e) {system. out. println (" The client socket does not exist. "); Checksocket () ;}} else {checksocket () ;}} private void checksocket () {try {socketclient = new socket (remoteaddress, remoteport); outputstream = socketclient. getoutputstream (); socketisexits = true;} catch (exception e) {socketisexits = false ;}}}

3. socketclient class:

package socket._5;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class SocketClient implements Runnable {public int remotePort = 5000;public String remoteAddress = "localhost";public static void main(String args[]) {SocketClient socketClient = new SocketClient();socketClient.run();}public SocketClient() {}public void run() {Socket socket = null;OutputStream outputStream = null;byte[] buffer;int size = 0;try {socket = new Socket(remoteAddress, remotePort);outputStream = socket.getOutputStream();System.out.println(socket);while (true) {System.out.println("input:");buffer = new byte[2048];size = System.in.read(buffer);if (size > 0) {outputStream.write(new String(buffer, 0, size).getBytes());outputStream.flush();}}} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (socket != null)socket.close();if (outputStream != null)outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}

Related Article

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.