java simple chat room

1. Tool class to close the stream:
package com.chat.demo01;

import java.io.Closeable;
import java.io.IOException;

/**
 * Tool to close the stream
 * @author snail
 *
 */
public class CloseUtil {
	public static void closeAll(Closeable... io) {
		for(Closeable temp : io)
		{
			try {
				temp.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
	}
}
2. The client Client opens up 2 threads (one receiving thread and one sending thread) in order to receive messages sent by multiple clients from the server.
<1> The thread where the client sends data
package com.chat.demo01;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Send data thread
 * @author snail
 *
 */
public class SendData implements Runnable{
	// console input stream
	private BufferedReader console;
	private String name;
	//pipe stream
	private DataOutputStream dos;
	private boolean isRuning = true;
	public SendData() {
		
		console = new BufferedReader(new InputStreamReader(System.in));
	}
	public SendData(Socket client, String name2) {
	
		this();
		try {
			dos = new DataOutputStream(client.getOutputStream());
			this.name = name;
			send(this.name);
		} catch (IOException e) {
			//e.printStackTrace();
			isRuning = false;
			CloseUtil.closeAll(dos, console);
		}
	}
	/**
	 * Get data from console
	 * @return
	 */
	private String getMsgfromConsole() {
		try {
			return console.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		return "";
	}
	/**
	 * send data
	 */
	public void send(String str) {
		String msg = str;
		if(null != msg && !msg.equals("")) {
			try {
				dos.writeUTF(msg);
				dos.flush();
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}
	}
	@Override
	public void run() {
		while(isRuning) {
			// thread body
			send(getMsgfromConsole());
		}
	}

}
<2> The thread where the client receives data
package com.chat.demo01;
/**
 * Receive data thread
 * @author snail
 *
 */

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

public class ReceiveData implements Runnable{
	//input stream
	private DataInputStream dis;
	private boolean isruning = true;
	public ReceiveData(Socket client) {
		try {
			dis = new DataInputStream(client.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			isruning = false;
		//	CloseUtil.closeAll(dis);
		}
	}
	public String receive() {
		try {
		 return	dis.readUTF();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			isruning = false;
			//CloseUtil.closeAll(dis);
		}
		return "No data sent";
	}
	@Override
	public void run() {
		while(isruning) {
			System.out.println(receive());
		}
	}
}
Client Client:
 
 
package com.chat.demo01;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Create a client. send data + receive data
 * write out data: output stream
 * Read data: input stream
 * @author snail
 *
 */
public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		System.out.println("Please enter a name: ");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String name = br.readLine();
	
		Socket client = new Socket("localhost", 9999);
		//Open up 2 threads to send and receive data
		new Thread(new SendData(client, name)).start();
		new Thread(new ReceiveData(client)).start();
	}

}
4. Server Server:
 
 
package com.chat.demo01;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import javax.print.attribute.standard.MediaSize.Other;
import javax.xml.crypto.Data;

/**
 * Create server: transfer station
 * @author snail
 *
 */
public class Server {
	//Client channel container
	private ArrayList<MyChannel> all =new ArrayList<MyChannel>();
	public void	 start() throws IOException {
		ServerSocket server = new ServerSocket(9999);
		// keep receiving the client's socket
		while(true)
		{
			Socket client = server.accept();
			MyChannel mychanel = new MyChannel (client);
			//Receive pipes from multiple clients
			all.add(mychanel);
			//current client player
			new Thread(mychanel).start();
		}
	
	}
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Server server = new Server();
		server.start();
	}
/**
 * A pipeline with the same client
 * @author snail
 *
 */
	private class MyChannel implements Runnable{
		private DataInputStream dis;
		private DataOutputStream dos;
		private boolean isruning = true;
		private String name;
		public MyChannel(Socket client) {
			// TODO Auto-generated constructor stub
			try {
				dis = new DataInputStream(client.getInputStream());
				dos = new DataOutputStream(client.getOutputStream());
				this.name = dis.readUTF();
				this.send("Welcome to the chat room");
				sendOthers(this.name+"Enter the chat room");
			} catch (IOException e) {
				isruning = false;
				CloseUtil.closeAll(dis, dos);
			}
			
		}
		/**
		 * Accepted data
		 * @return
		 */
		public String receive() {
			try {
				return dis.readUTF();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				isruning = false;
				CloseUtil.closeAll( dis);
				all.remove(this);
			}
			return "";
		}
		/**
		 * Send multiple clients
		 */
		private void sendOthers(String msg1) {
			String msg =msg1; //your content
			
			for(MyChannel other: all)
			{
				if(other == this)
					continue;
				// send to others
				other.send(msg);
			}
			
		}
		/**
		 * sent data
		 * @param msg
		 */
		public void send(String msg)
		{
			if(null == msg && msg.equals(""))
				return;
			try {
				dos.writeUTF(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				isruning = false;
				CloseUtil.closeAll(dos);
			
			}
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(isruning) {
				sendOthers(receive());
			}
		}
		
	}

}



 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325782105&siteId=291194637