
- 用户昵称:aflfte2011
服务器端 客户端: package com.aflfte.chat05; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; /** * 在线聊天室客户端 * 1、实现多个客户可以正常收发多条信息 * * * @author jinhao * */ public class Client { public static void main(String[] args) throws Exception { System.out.println("----Client----"); System.out.println("请输入用户名:"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String name=br.readLine(); //与服务器建立连接 Socket client=new Socket("127.0.0.1",8899); //客户端发送消息 new Thread(new Send(client,name)).start(); new Thread(new Receive(client)).start(); } } package com.aflfte.chat05; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; /** * 接收消息 * @author jinhao * */ public class Receive implements Runnable { private DataInputStream dis; private Socket client; private boolean isRuning=false; public Receive(Socket client) { super(); this.client = client; try { dis=new DataInputStream(client.getInputStream()); isRuning=true; } catch (IOException e) { System.out.println("Receive()"); release(); } } private void release() { this.isRuning=false; Utils.close(dis,client); } private String receive() { String datas=""; try { datas = dis.readUTF(); return datas; } catch (IOException e) { System.out.println("receive()"); release(); } return ""; } @Override public void run() { while(isRuning){ String msg=receive(); if(!msg.equals("")) { System.out.println(msg); } } } } package com.aflfte.chat05; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; /** * 发送消息 * @author jinhao * */ public class Send implements Runnable { private BufferedReader into; private DataOutputStream dos; private Socket client; private boolean isRuning=false; private String name; public Send(Socket client,String name) { this.client=client; this.name=name; into=new BufferedReader(new InputStreamReader(System.in)); try { dos=new DataOutputStream(client.getOutputStream()); isRuning=true; //发送名称 send(name); } catch (IOException e) { System.out.println("Send()"); release(); } } private void release() { this.isRuning=false; Utils.close(dos,client); } public String msg() { try { return into.readLine(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return null; } public void send(String msg) { try { dos.writeUTF(msg); dos.flush(); } catch (IOException e) { System.out.println("send()"); release(); } } @Override public void run() { while(isRuning) { String msg=msg(); if(!msg.equals("")) { send(msg); } } } } import java.io.Closeable; /** * 释放资源工具类 * * @author jinhao * */ public class Utils { public static void close(Closeable...targets) { for(Closeable target:targets) { try { if(target!=null) { target.close(); } }catch(Exception e){ e.printStackTrace(); } } } } « 注解创建与反射使用 | TCP实现多用户登录» |