JavaSE使用socket与线程实现控制台版的聊天室功能

服务器server端:

	private ServerSocket server;// 创建了ServerSocket对象
	// 存放所有客户端输出流的集合,并初始化
	private List<PrintWriter> allOut = new ArrayList<PrintWriter>();

	// 向集合中添加元素
	private synchronized void addOut(PrintWriter out) {
		allOut.add(out);
	}

	// 从集合中删除元素
	private synchronized void removeOut(PrintWriter out) {
		allOut.remove(out);
	}

	// 遍历集合向所有的客户端发送信息
	private synchronized void sendMessage(String msg) {
		for (PrintWriter out : allOut) {
			out.println(msg);
		}

	}

	/**
	 * 构造方法,用来初始化ServerSocket
	 * 
	 * @throws IOException
	 */
	public Server() throws IOException {
		try {
			server = new ServerSocket(8088);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public void start() throws IOException {
		while (true) {
			try {
				Socket socket = server.accept();
				/**
				 * 当一个客户端连接后,应该启动一个线程,来负责与客户端的交互 这样才能循环接待不同的客户端
				 */
				ClientHandler hander = new ClientHandler(socket);
				Thread thread = new Thread(hander);
				// 启动线程
				thread.start();
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			}
		}
	}

	public static void main(String[] args) {
		Server server = null;
		try {
			server = new Server();
			server.start();
		} catch (IOException e) {
			System.out.println("服务器启动失败");
		}
	}

	/**
	 * 启动线程的成员内部类
	 * 
	 * @author Admin
	 * 
	 */

	class ClientHandler implements Runnable {
		private Socket socket;

		public ClientHandler(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			PrintWriter writer = null;
			try {
				// 向客户端发送信息
				writer = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				addOut(writer);
				// 读取客户端的信息
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream(), "utf-8"));
				String msg = null;

				while ((msg = reader.readLine()) != null) {
					// 将客户端发送过来的信息转发给客户端
					sendMessage(msg);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// 处理客户端断开连接后的工作
				// 将客户端的输出流从集合中移除
				removeOut(writer);
			}
		}
	}
客户端client端:

	// 创建与服务端通讯的Socket
	private Socket socket;

	public Client() throws IOException {
		try {
			socket = new Socket("localhost", 8088);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}

	// 客户端开始工作的方法
	public void start() {
		// 启动线程,用于读取服务端发送过来的信息
		ServerHandler handler = new ServerHandler();
		Thread thread = new Thread(handler);
		// 启动线程
		thread.start();
		/**
		 * 循环从控制台输入信息发送至服务端
		 */
		Scanner sca = new Scanner(System.in);
		try {
			PrintWriter writer = new PrintWriter(new OutputStreamWriter(
					socket.getOutputStream(), "utf-8"), true);
			String msg = null;
			while (true) {
				msg = sca.nextLine();
				writer.println(msg);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Client c = null;
		try {
			c = new Client();
			c.start();
		} catch (IOException e) {
			System.out.println("连接失败");
		}
	}

	// 读取服务端发送过来的信息的线程
	class ServerHandler implements Runnable {

		@Override
		public void run() {
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream(), "utf-8"));
				String msg = null;
				while ((msg = reader.readLine()) != null) {
					System.out.println(msg);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
部分代码如下:client: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; /** * * @author Administrator */ import java.awt.*; import java.io.*; import java.net.*; import java.applet.*; import java.util.Hashtable; public class ClientChat extends Applet implements Runnable { Socket socket=null; DataInputStream in=null; DataOutputStream out=null; InputNameTextField 用户提交昵称界面=null; ChatArea 用户聊天界面=null; Hashtable listTable; Label 提示条; Panel north, center; Thread thread; public void init() { int width=getSize().width; int height=getSize().height; listTable=new Hashtable(); setLayout(new BorderLayout()); 用户提交昵称界面=new InputNameTextField(listTable); int h=用户提交昵称界面.getSize().height; 用户聊天界面=new ChatArea("",listTable,width,height-(h+5)); 用户聊天界面.setVisible(false); 提示条=new Label("正在连接到服务器,请稍等...",Label.CENTER); 提示条.setForeground(Color.red); north=new Panel(new FlowLayout(FlowLayout.LEFT)); center=new Panel(); north.add(用户提交昵称界面); north.add(提示条); center.add(用户聊天界面); add(north,BorderLayout.NORTH); add(center,BorderLayout.CENTER); validate(); } public void start() { if(socket!=null&&in!=null&&out!=null) { try { socket.close(); in.close(); out.close(); 用户聊天界面.setVisible(false); } catch(Exception ee) { } } try { socket = new Socket(this.getCodeBase().getHost(), 6666); in=new DataInputStream(socket.getInputStream()); out=new DataOutputStream(socket.getOutputStream()); } catch (IOException ee) { 提示条.setText("连接失败"); } if(socket!=null) { InetAddress address=socket.getInetAddress(); 提示条.setText("连接:"+address+"成功"); 用户提交昵称界面.setSocketConnection(socket,in,out); north.validate(); } if(thread==null) { thread=new Thread(this); thread.start(); } } public void stop() { try { socket.close(); thread=null; } catch(IOException e) { this.showStatus(e.toString()); } } public void run() { while(thread!=null) { if(用户提交昵称界面.get能否聊天()==true) { 用户聊天界面.setVisible(true); 用户聊天界面.setName(用户提交昵称界面.getName()); 用户聊天界面.setSocketConnection(socket,in,out); 提示条.setText("祝聊天愉快!"); center.validate(); break; } try { Thread.sleep(100); } catch(Exception e) { } } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值