Java简单的局域网多人聊天室

实现功能:

1.显示用户上下线信息

2.发送信息后全部人可见

3.特定格式的信息可以实现私信功能

 

服务器端

package com.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.swing.text.MaskFormatter;


public class Server {
	private ServerSocket server;            //与用户连接的socket套接字
	private Map pws;    //用户名字为唯一标识符,与对应的输出流做映射关系

	/*初始化socket和Map*/
	public Server() {
		try {
			server = new ServerSocket(8091);
			pws=new HashMap();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*存储用户名字-输出流映射*/
	public void savePw(String name,PrintWriter pw){
		if(pw==null){
			return;
		}
		pws.put(name, pw);
	}
	
	/*向全部用户发送数据*/
	public void sendToAll(String msg){
		if(msg==null||msg.trim().length()==0){
			return;
		}
		Set names=pws.keySet();    //获取用户名字集
		for(String name:names){			   //遍历名字集,获取对应的用户输出流发送数据
			PrintWriter pw=pws.get(name);
			pw.println(msg);
		}
	}
	
	//私信功能,server接受到的格式为senderName:@receiverName:msg  
	public boolean sendToOne(String msg){
		if(!msg.contains("@")){
			return false;
		}
		if((!msg.contains(":"))&&(!msg.contains(";"))){
			return false;
		}
		System.out.println(msg);
		String[] arr=msg.split(":");  //获取到["sender","@receiver","msg"]
		String senderName=arr[0];
		String receiverName=arr[1].substring(1);
		String message="";
		for(int i=2;i

 

客户端

package com.chat;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import javax.swing.JTextArea;

/**
 * 1.界面设计
 * 		(1)窗口JFrame
 * 		(2)面板JPanel:testPanel
 * 		(3)两个文本域JTextArea: 显示文本域showText,输入文本域inputText
 */
public class Client extends JFrame{
	private Socket socket;
	private String name;
	private JPanel textPanel;
	private JTextArea showText;
	private JTextArea inputText;
	
	/*socket,name初始化以及窗口的初始化*/
	public Client(String name) {
		try {
			this.name = name;
			this.setTitle(name);
			socket=new Socket("localhost",8091);
			textPanel=new JPanel();
			showText =new JTextArea(12,42);
			inputText=new JTextArea(4,42);
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*设置窗口具体属性*/
	public void init() {
		this.setSize(500, 310);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(false);
		this.setLayout(new BorderLayout());
		this.add(textPanel,BorderLayout.CENTER);
		
		textPanel.setLayout(new FlowLayout());
		
		showText.setEditable(false);         //显示文本域不可编辑
		/*添加垂直滚动条*/
		JScrollPane scroll=new JScrollPane(showText); 
		scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		textPanel.add(scroll);
		
		inputText.setLineWrap(true);        //输入文本域自动换行
		scroll =new JScrollPane(inputText);
		scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		textPanel.add(scroll);
	
		this.setVisible(true);
	}
	
	/*向服务器发送信息的方法*/
	public void sendMessage(String message){
		if(message==null||message.trim().length()==0){
			return;
		}
		OutputStream os =null;
		PrintWriter pw=null;
		try {
			os =socket.getOutputStream();
			pw=new PrintWriter(new OutputStreamWriter(os),true);
			pw.println(message);
		} catch (Exception e) {
		}
	}
	
	
	
	/*在显示文本域中显示服务器发送过来的信息的方法*/
	public void showMessage(){
		try {
			InputStream is=socket.getInputStream();
			BufferedReader br=new BufferedReader(new InputStreamReader(is, "utf-8"));
			String line="";
			while((line=br.readLine())!=null){
				showText.append(line+"\r\n");      //显示后自动换行
				showText.setCaretPosition(showText.getText().length());   //实现滚动条随着行数自动滚动
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void start(){
		sendMessage(name);      //连接上服务器立即发送用户名
		KeyAdapter l=new KeyAdapter() {
			public void keyReleased(KeyEvent e){
				if(e.getKeyCode()==KeyEvent.VK_ENTER){
					String content=inputText.getText().trim();
					sendMessage(name+":"+content);      //发送格式:  senderName:msg
					inputText.setText("");      //发送完后清空输入文本域
				}
			}
		};
			
		inputText.addKeyListener(l);   //将事件绑定到输入文本域上inputText
		inputText.requestFocus();  //获取焦点
		showMessage();    //循环接受服务器返回的数据
	}
	
	
	
	public static void main(String[] args) {
		Client c=new Client("zhangsan");
		c.start();
	}
}

 

 

 

你可能感兴趣的:(Java,IO)