读书人

Socket多线程习题

发布时间: 2012-10-31 14:37:31 作者: rapoo

Socket多线程练习
这个程序现在来看简直就是弱爆了。。。勿看,没有参考价值

写一个socket,多线程相关的练习。
就是经典的客户端服务器聊天例子啦
看了一些写法,也不知道哪个是对的

在服务器端维护了一个请求list,每个客户端的请求服务器端新起一个Thread

当客户端退出时将该thread从list中去除

该什么时候去删除,怎么去删除。。。不会了

请各位指点下,谢谢了

import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.EOFException;import java.io.IOException;import java.net.BindException;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ChatServer {List<Client> clients = new ArrayList<Client>();public static void main(String[] args) {new ChatServer().start();}public void start() {boolean started = false;ServerSocket ss = null;try {ss = new ServerSocket(8888);started = true;} catch (BindException e) {System.out.println("端口正在被使用,请关闭相应程序!");System.exit(0);} catch (IOException e) {e.printStackTrace();}try {while (started) {Socket s = ss.accept();Client c = new Client(s);clients.add(c);System.out.println("a client connected!");new Thread(c).start();}} catch (IOException e) {e.printStackTrace();} finally {try {ss.close();} catch (IOException e) {e.printStackTrace();}}}/** * 每个请求过来启用一个线程来处理<br> */private class Client implements Runnable {Socket socket = null;DataInputStream dis = null;DataOutputStream dos = null;boolean connected = false;Client(Socket s) {try {this.socket = s;dis = new DataInputStream(s.getInputStream());dos = new DataOutputStream(s.getOutputStream());connected = true;} catch (IOException e) {e.printStackTrace();}}public void run() {while (connected) {try {Iterator<Client> it = clients.iterator();String msg = dis.readUTF();while (it.hasNext()) {Client c = it.next();c.send(msg);}} catch (EOFException eof) {connected = false;// 需要在序列中将退出的client去除,// 迭代过程中// 不能使用Collection本身的remove方法,// 会抛出java.util.ConcurrentModificationException// 使用iterator的remove方法} catch (IOException e) {e.printStackTrace();}}}private void send(String str) throws IOException {dos.writeUTF(str);}}}
1 楼 Blithe 2009-05-05 在出异常的时候把时候把他删了
clients.remove(s); 2 楼 lucane 2009-05-10 Blithe 写道
在出异常的时候把时候把他删了clients.remove(s);

应该是出异常的时候删,但我这里删了报错
我看有些人list里面放的是Socket,我放的是Client
这个有影响吗

读书人网 >软件架构设计

热点推荐