Socket (Java) Simple multiple client, server-side communication (multithreading)

Source: Internet
Author: User
Tags flush getmessage int size
Original works, allow reprint, reprint, please be sure to hyperlink form to indicate the original source of the article, author information and this statement. Otherwise, legal liability will be held. http://blog.csdn.net/love254443233/article/details/7897269


Realize:

Client: Multiple sockets (multiple ports), where one port for a client is used to receive messages sent by the server and one to send messages to the server. Other clients only have the ability to send messages.

Service side: Two sockets, one for the loop to receive the client sent over the socket request. A message is sent automatically to the client by the receiving hand.

Note: run Mysocketserver First, then mysocketclient, and finally socketclient;mysocketclient, socketclient send message 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-side------listening ...");
			while (true) {Socket socket = s.accept ();
			SYSTEM.OUT.PRINTLN ("Access socket:" + socket);
			GetMessage GetMessage = new GetMessage (socket);
			Thread thread = new Thread (getMessage);
		Thread.Start ();
	}}///Receive Message class GetMessage implements Runnable {private int remoteport = 5001;
	Private String remoetaddress = "localhost";
	Private InputStream InputStream;
	Private OutputStream OutputStream;
	Private Socket Socketget;
	Private Socket socketsendmessage;
	Private 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 String (buffer, 0, N);
				System.out.print ("Client:" + str);
			SendMessage ();
				catch (IOException e) {e.printstacktrace ();
			Break
			} if (Str.equals ("Q")) {break;
			The try {if (socketget!= null) socketget.close ();
		if (InputStream!= null) inputstream.close ();
				The catch (Exception e) {}}//Send message public void SendMessage () throws IOException {if (socketisexits) {try {
				String input = "= = =" + (sum++);
				SYSTEM.OUT.PRINTLN ("service-side Send socket:" + this.socketsendmessage);
				Outputstream.write (Input.getbytes ());
				SYSTEM.OUT.PRINTLN ("server:" + input);
			Outputstream.flush ();
			catch (Exception e) {	SYSTEM.OUT.PRINTLN ("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 csendmessage = new Csendmessage ();
		Thread thread2 = new Thread (csendmessage);

		Thread2.start ();
		ServerSocket serversocket = new ServerSocket (localhostport);
			while (true) {Socket socketserver = serversocket.accept ();
			Cgetmessage getMessage = new Cgetmessage (socketserver);
			Thread thread = new Thread (getMessage);
		Thread.Start ();
	}///Receive Message class Cgetmessage implements Runnable {private InputStream inputstream;
	private socket 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) {}}}//Send Message class Csendmessage implements Runnable {Private Boolean socketisexits = False
	;
	Private OutputStream 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 ("Please 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 (); The catch (Exception e) {System.out.println ("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 ();
		A 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 (); }
		}
		
	}
}

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.