今天我们来制作 Flash 聊天室,学习使用 Socket 类,用 Java 作后台,开发一个 C / S 架构的多人聊天程序。首先,设计用户界面。
一、界面设计
界面的元件全部使用 Flash CS3 自带的组件:
首先,放入 TextInput 组件(实例名 input_txt),作为用户输入;
再放入 Button 组件(实例名 submit_btn),用于提交输入的信息;
最后放入 TextArea 组件(实例名 output_txt),显示聊天信息。
二、组件参数初始化
由于客户端代码不是很多,我们这次就写在动作帧上:
// ************ 组件参数初始化 ************ submit_btn.label = "发送消息"; output_txt.editable = false; // 设置各组件中字体的大小 input_txt.setStyle("textFormat", new TextFormat(null, 15)); output_txt.setStyle("textFormat", new TextFormat(null, 15)); submit_btn.setStyle("textFormat", new TextFormat(null, 15, null, true)); // 当按下回车或点击 submit_btn 按钮后调用事件处理函数 submit_btn.addEventListener(MouseEvent.CLICK, sendMessage); addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); // 事件处理函数 function onKeyDown(evt:KeyboardEvent):void { if (evt.keyCode == Keyboard.ENTER) { sendMessage(null); } } function sendMessage(evt:Event):void { // 测试:将 input_txt 的内容输出到 output_txt 中 output_txt.appendText(input_txt.text + "\n"); // 清空 input_txt,并设置焦点到 input_txt input_txt.text = ""; stage.focus = input_txt; }三、编写客户端 Socket
1. 首先,Socket 连接非常简单:
var socket:Socket = new Socket(); socket.connect("127.0.0.1", 8888);
function sendMessage(evt:Event):void { var bytes:ByteArray = new ByteArray(); bytes.writeUTFBytes(input_txt.text + "\n"); socket.writeBytes(bytes); socket.flush(); // 清空 input_txt,并设置焦点到 input_txt input_txt.text = ""; stage.focus = input_txt; }
// 当客户端 socket 收到数据后会调用 readMessage() 函数 socket.addEventListener(ProgressEvent.SOCKET_DATA, readMessage); function readMessage(evt:ProgressEvent):void { output_txt.appendText(socket.readUTF() + "\n"); }四、Flash 客户端全部脚本
// ************ 组件参数初始化 ************ submit_btn.label = "发送消息"; output_txt.editable = false; input_txt.setStyle("textFormat", new TextFormat(null, 15)); output_txt.setStyle("textFormat", new TextFormat(null, 15)); submit_btn.setStyle("textFormat", new TextFormat(null, 15, null, true)); submit_btn.addEventListener(MouseEvent.CLICK, sendMessage); addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); function onKeyDown(evt:KeyboardEvent):void { if (evt.keyCode == Keyboard.ENTER) { sendMessage(null); } } function sendMessage(evt:Event):void { var bytes:ByteArray = new ByteArray(); bytes.writeUTFBytes(input_txt.text + "\n"); socket.writeBytes(bytes); socket.flush(); input_txt.text = ""; stage.focus = input_txt; } // ************ 客户端 Socket ************ var socket:Socket = new Socket(); socket.connect("127.0.0.1", 8888); socket.addEventListener(ProgressEvent.SOCKET_DATA, readMessage); function readMessage(evt:ProgressEvent):void { output_txt.appendText(socket.readUTF() + "\n"); }
ServerSocket socketServer = new ServerSocket(8888); System.out.println("服务器已启动,等待客户端连接"); // accept() 方法是阻塞式的,当有客户端连接成功后才继续执行 Socket socket = socketServer.accept(); System.out.println("客户端连接成功");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
while (true) { // readLine() 方法也是阻塞式的,当客户端有消息发来就读取,否则就一直等待 String msg = reader.readLine(); // 当客户端发送的字符串为 null 时,说明客户端已经关闭,此时退出循环 if (msg == null) { System.out.println("客户端已离开"); break; } // 将读入的信息加工后再写回客户端 writer.writeUTF("写回客户端的" + msg); }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class FlashScoket { private List<Client> clientList = new ArrayList<Client>(); public static void main(String[] args) { new FlashScoket().runSocket(); } private void runSocket() { try { ServerSocket socketServer = new ServerSocket(8888); System.out.println("服务器已启动,等待客户端连接"); while (true) { // accept() 方法是阻塞式的,当有客户端连接成功后才继续执行 Socket socket = socketServer.accept(); System.out.println("客户端连接成功"); // 实例化一个 Client 对象,并启动该线程 Client client = new Client(socket); clientList.add(client); client.start(); } } catch (IOException e) { e.printStackTrace(); } } class Client extends Thread { private Socket socket; private BufferedReader reader; private DataOutputStream writer; private Client(Socket socket) { this.socket = socket; try { // 获得输入流和输出流,输入流为 BufferedReader 类型,输出流为 DataOutputStream 类型 reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new DataOutputStream(socket.getOutputStream()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { while (true) { // readLine() 方法也是阻塞式的,当客户端有消息发来就读取,否则就一直等待 String msg = reader.readLine(); // 当客户端发送的字符串为 null 时,说明客户端已经关闭,此时退出循环 if (msg == null) { clientList.remove(this); System.out.println("客户端已离开"); break; } // 将读入的内容写给每个客户端 for (Iterator<Client> it = clientList.iterator(); it.hasNext();) { Client client = it.next(); client.getWriter().writeUTF(msg); } } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭 socket 及相关资源 try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } } } public DataOutputStream getWriter() { return writer; } } }
output_txt.verticalScrollBar.scrollPosition = output_txt.verticalScrollBar.maxScrollPosition;
socket.addEventListener(IOErrorEvent.IO_ERROR, socketIOError); function socketIOError(evt:IOErrorEvent):void { output_txt.appendText("服务器端尚未开启,请稍后再试\n"); }
if (input_txt.text == "") { return; }
bytes.writeUTFBytes(userName + " : " + input_txt.text + "\n");
bytes.writeUTFBytes("<font color='#0000FF'>" + userName + " : </font>" + input_txt.text + "\n");