public void disconnect() { // 断开连接函数 try { dos.close(); // 关闭输出流 dis.close(); // 关闭输入流 s.close(); // 关闭断口
} catch (IOException e) { e.printStackTrace(); } }
private class TFListener implements ActionListener { // 声明文本行的事件监听器类
public void actionPerformed(ActionEvent e) { // 覆写文本域的事件响应方法
Date d = new Date();
String str = d.toLocaleString() +\:巴卫 说: \ +tfTxt.getText().trim(); // 获取文本行的内容 tfTxt.setText(\); // 把文本行的内容显示到文本域 try { dos.writeUTF(str); // 向输出流缓冲写数据 dos.flush(); // 数据发送 } catch (IOException e1) { e1.printStackTrace(); } } }
private class RecvThread implements Runnable {
// 声明线程类,用来接收服务器对应线程发来的消息 public void run() { // 线程启动函数 try { while (bConnected) {
}
String str = dis.readUTF(); // 读取缓冲区数据
taContent.setText(taContent.getText() + str + '\\n'); // 把缓冲区内容显示在文本域上
9
}
}
}
} catch (SocketException e) { System.out.println(\退出了,bye!\); // 对方退出提示,非正常退出,像断电之类的 } catch (EOFException e) { System.out.println(\退出了,bye - bye!\); // 正常退出提示 } catch (IOException e) { // 捕获其他异常 e.printStackTrace(); }
2.服务器端
package src; import java.io.*; import java.net.*; import java.util.*; //引入线程相关包 public class Server { // 定义服务器端类 boolean started = false; // 服务器启动标志 ServerSocket ss = null; List
10
while (started) { Socket s = ss.accept(); // 服务器启动后,接收自客户端的消息 Client c = new Client(s); // 创建客户端进程 new Thread(c).start(); // 启动客户端进程 clients.add(c); // 加入到客户端列表 }
} catch (IOException e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } }
class Client implements Runnable { // 声明客户端线程类 private Socket s;
private DataInputStream dis = null; private DataOutputStream dos = null; private boolean bConnected = false; public Client(Socket s) { // 客户端线程构造函数 this.s = s; try { dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); bConnected = true; } catch (IOException e) { e.printStackTrace(); } }
public void send(String str) { // 发送消息函数 try { dos.writeUTF(str); } catch (IOException e) { clients.remove(this); System.out.println(\对方退出了!\);
11
} }
public void run() { }
}
}
try { while (bConnected) { // 向每个客户端发消息 String str = dis.readUTF(); for (int i = 0; i < clients.size(); i++) { Client c = clients.get(i); c.send(str); } } } catch (EOFException e) { System.out.println(\客户端退出!\); } catch (IOException e) { e.printStackTrace(); } finally { try { if (dis != null) dis.close(); if (dos != null) dos.close(); if (s != null) { s.close(); } } catch (IOException e1) { e1.printStackTrace(); } }
12
课程设计成绩评定表
学生姓名 专业班级 设计题目 实现一个一对一的聊天程序 指导教师评语及意见: 指导教师评阅成绩: 指导教师签字: 年 月 日