JAVA作业 sockect编程实现聊天室(一服务器多客户端)

题目:利用多线程、Socket编程、GUI编写一个聊天室,客户端可以发送信息,服务器将接收到的每个用户端的信息实时发送给其他客户端。(提示:服务器为每个客户端启动一个单独线程,客户端启动一个单独线程接收服务器发送来的其他客户端的信息)

思想: 唔由于该死的拖延症现在才做最后这道做烂的题目,基础多线程、Socket编程练习,各种异常注意处理(折磨

实现客户端如图:

JAVA作业 sockect编程实现聊天室(一服务器多客户端)_第1张图片

实现代码:

package chatRoom;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

/**
* @author TX
* @version 创建时间:2016年12月20日 上午10:59:06
* 客户端
*/
public class Client {
	private Socket socket;
	private DataInputStream dis;
	private DataOutputStream dos;
	public PrintStream print;
	private TextArea ta;
	private TextField tf;
	
	public void connect()
	{
		try {
			socket = new Socket("127.0.0.1", 8888);
			print = new PrintStream(socket.getOutputStream());
			dis = new DataInputStream(socket.getInputStream());
			dos = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void createGUI()
	{
		Frame frame = new Frame("客户端");
		ta = new TextArea();
		tf = new TextField();
		Button send = new Button("发送");
		Panel pan = new Panel();
		pan.setLayout(new BorderLayout());
		pan.add(tf, "Center");
		pan.add(send, "East");
		frame.add(ta, "Center");
		frame.add(pan, "South");
	
		send.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				sendMessage();
				tf.requestFocus();
			}
		});
		
		tf.addKeyListener(new KeyAdapter(){
			public void keyPressed(KeyEvent e){
				if(e.getKeyChar() == '\n'){
					sendMessage();
				}
			}
		});
		
		frame.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e) {
				try {
					if(socket!=null){
						socket.close();
						System.exit(0);
					}
				} catch (IOException e1) {
					System.out.printf("客户端退出……");
					e1.printStackTrace();
				}
		     }
		});
		frame.setSize(400, 400);
		frame.setVisible(true);
	}
	
	public void sendMessage()
	{
		if(tf.getText().equals("")==false)
		{
			String str = tf.getText();
			print.println(str);
			tf.setText("");
		}
	}
	public DataInputStream getDis() {
		return dis;
	}

	public DataOutputStream getDos() {
		return dos;
	}

	public TextArea getTa() {
		return ta;
	}
	
	public Socket getSocket() {
		return socket;
	}

	public static void main(String args[]) 
	{
		Client tc = new Client();
		tc.createGUI();
		tc.connect();
		new ClientReadThr(tc).start();
	}
	
}

package chatRoom;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;

/**
* @author TX
* @version 创建时间:2016年12月20日 上午11:03:48
* 客户端读取信息线程
*/
public class ClientReadThr extends Thread{
	private Client client;
	boolean bConnected=false;
	BufferedReader reader=null;
	
	public ClientReadThr(Client client){
		this.client = client;
	}
	public void run(){
		bConnected=true;
		reader=new BufferedReader(new InputStreamReader(client.getDis()));
		try{
			while(bConnected)
			{ 
				String message = "";
				message = reader.readLine();
				if(message == null || "".equals(message) == true)
				{			
					bConnected = false;
				}
				client.getTa().append(message + "\n");
			}					
		}catch(SocketException e){	
		}catch(EOFException e){
		}catch(IOException e) {
		}finally{
			try {
				if(reader!=null) reader.close();
				if(client.getSocket() != null) client.getSocket().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

package chatRoom;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

/**
* @author TX
* @version 创建时间:2016年12月12日 下午7:32:40
* 服务器端
*/
public class Server {
	private ServerSocket server;
	private Socket clients;
	public ServerReadThr client;
	public static ArrayList clientList = new ArrayList();
	public PrintStream print;
	
	public void connect()
	{
		try {
			server = new ServerSocket(8888);
			while(true)
			{
				System.out.println("等待客户端的连接");
				clients = server.accept();
				InetAddress inet = clients.getInetAddress();
				System.out.println("--建立连接:" + inet.toString());	
				client = new ServerReadThr(clients);
				clientList.add(client);
				client.start();
			}
		} catch(BindException e){
			System.out.println("端口使用中,请关掉相关程序并重新运行服务器!");
			System.exit(0);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String args[]) 
	{
		 Server ts = new Server();
		 ts.connect();
	}
	
}

package chatRoom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
* @author TX
* @version 创建时间:2016年12月20日 上午10:45:58
* 服务器端读取并转发线程
*/
public class ServerReadThr extends Thread{
	private Socket socket=null;
	private PrintStream print=null;
	private BufferedReader reader=null;
	private boolean started=false;
	
	public ServerReadThr(Socket socketatServer)
	{
		this.socket=socketatServer;
		try {
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			print = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}

	public void send(String str)
	{
		print.println(str);
	}
	
	public void run() 
	{
		String str = ""; 
		started=true;
		try{
			while(started)
			{
		    	try {
		    		str = reader.readLine();
		    		if(str == null || "".equals(str))
		    		{
		    			System.out.printf("断开连接");
		    			break;
		    		}
		    		for(int i = 0; i < Server.clientList.size();i++)
		    		{
		    			ServerReadThr client = Server.clientList.get(i);
		    			client.send("Client:" + str);
		    		}
		    	} catch (IOException e) {
		    		e.printStackTrace();
		    	}
			}
		}catch(Exception e){
			System.out.println("连接中断");
		}finally{
			if(socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}

你可能感兴趣的:(Java)