使用Java编写Socket服务器,并且与Flex通信(二)

通过对第一个例子的学习,已经对Socket有了一个比较清晰的认识。

不过第一个例子有一个问题,就是只能有一个客户端调用,下面我们把第一个例子的代码做一个改进,改成多客户端调用的。

 

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.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 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);
                    }
                });
			}
		} 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的代码不用改,到此就可以使用多客户端同时连接响应了

posted @ 2010-12-07 18:06  魔豆  阅读(539)  评论(0编辑  收藏  举报