使用Java编写Socket服务器,并且与Flex通信(三)
掌握在通过客户端给服务端发送信息的例子,接着我们来通过服务端给客户端发信息
Java服务端代码:
Test2.java
package com.ruiri.app; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Shell; public class Test2 { private List list; protected Shell shell; private ServerSocket server; private Socket socket; /** * Launch the application * * @param args */ public static void main(String[] args) { try { Test2 window = new Test2(); window.open(); } catch (Exception e) { e.printStackTrace(); } } /** * Open the window */ public void open() { final Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } /** * Create contents of the window */ protected void createContents() { shell = new Shell(); shell.setSize(286, 375); shell.setText("socket服务器"); final Button button = new Button(shell, SWT.NONE); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent e) { Runnable runnable = new Runnable() { public void run() { try { server = new ServerSocket(719); Display.getDefault().asyncExec(new Runnable() { public void run() { list.add("服务器等待"); } }); while (true) { socket = server.accept(); Display.getDefault().asyncExec(new Runnable() { public void run() { list.add("已与客户机连接"); } }); SocketThread thread = new SocketThread(socket,list); thread.start(); } } catch (IOException e) { e.printStackTrace(); } finally { if (server != null) { try { if (!server.isClosed()) { server.close(); Display.getDefault().asyncExec( new Runnable() { public void run() { list.add("服务器断开"); } }); } } catch (IOException e1) { e1.printStackTrace(); } } } } }; Thread thread = new Thread(runnable); thread.start(); } }); button.setText("开启socket"); button.setBounds(42, 316, 72, 22); list = new List(shell, SWT.V_SCROLL | SWT.BORDER | SWT.H_SCROLL); list.setBounds(26, 10, 217, 300); final Button button_1 = new Button(shell, SWT.NONE); button_1.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent e) { try { if (server != null) { server.close(); server = null; } Display.getDefault().asyncExec(new Runnable() { public void run() { list.add("服务器断开"); } }); } catch (IOException e1) { e1.printStackTrace(); } } }); button_1.setText("关闭socket"); button_1.setBounds(154, 316, 72, 22); // } }
SocketThread.java
package com.ruiri.app; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.List; public class SocketThread extends Thread { public Socket socket; public List list = null; private BufferedReader reader; private DataOutputStream writer; private String str = ""; public SocketThread(Socket socket,final List list) { this.socket = socket; this.list = list; } public void run() { try { reader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); while(true) { str = reader.readLine(); if(str==null) break; Display.getDefault().asyncExec(new Runnable() { public void run() { list.add(str); } }); writer=new DataOutputStream(socket.getOutputStream()); writer.writeUTF("服务器端发送的消息"); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if(reader!=null) reader.close(); if(socket!=null) socket.close(); } catch (IOException e) { e.printStackTrace(); } Display.getDefault().asyncExec(new Runnable() { public void run() { list.add("已与客户机断开"); } }); } } }
Flex客户端代码:
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)"> <s:layout> <s:BasicLayout/> </s:layout> <fx:Script> <![CDATA[ import mx.controls.Alert; import mx.events.FlexEvent; private var socket:Socket; protected function application1_creationCompleteHandler(event:FlexEvent):void { socket=new Socket();//创建Socket对象 socket.connect("localhost",719); //连接服务器 socket.addEventListener(Event.CONNECT,connectFun);//监听是否连接上服务器 socket.addEventListener(Event.CLOSE,closeFun);//监听套接字连接是否关闭 socket.addEventListener(ProgressEvent.SOCKET_DATA,progressFun); } private function connectFun(event:Event):void { jText.text+="已经成功连接到服务器!\n"; } private function closeFun(event:Event):void { jText.text+="和服务器断开!\n" } private function progressFun(event:ProgressEvent):void { var msg:String=""; while(socket.bytesAvailable) { jText.text+=socket.readUTF()+"\n"; } } protected function button2_clickHandler(event:MouseEvent):void { var message:ByteArray=new ByteArray();//新建一个ByteArray存放数据 message.writeUTFBytes(msg.text +"\r\n");//写入数据,writeUTFBytes方法,以utf-8格式传数据避免中文乱码 socket.writeBytes(message); //写入Socket的缓冲区 socket.flush(); //调用flush方法发送信息 msg.text=""; //清空发言框 } ]]> </fx:Script> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <s:TextArea id="jText" x="139" y="129"/> <s:TextInput id="msg" x="139" y="325" width="188"/> <s:Button x="361" y="326" label="按钮" click="button2_clickHandler(event)"/> </s:Application>
呼呼,到此为止,对Socket的学习就告一段落了,在这些技术的基础上,可以做一个简单的聊天室,有兴趣的可以自己尝试下。
网上也有现成的聊天室例子:http://space.flash8.net/bbs/thread-349661-1-1.html
关于Socket的这三篇文章写的有点乱,代码也不是很完善,有时间再整理了。