Chat聊天 - 服务器端

[quote]ChatServer.java[/quote]

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.net.SocketException;
import java.util.ArrayList;
import java.util.List;

/**
* 服务器端
* @author Administrator
*/
public class ChatServer {

private ServerSocket ss = null;
//解决空指针问题;
private boolean started = false;
//使用了乏型把每一个客户端放在一个数组里面;
List<Client> lists = new ArrayList<Client>();

public static void main(String[] args) {
new ChatServer().start();
}

//连接客户端
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("Server is being used!");
System.out.println("Please shutdown Server!");
System.exit(0);
} catch (IOException ex) {
ex.printStackTrace();
}


try {
while (started) {
Socket s = ss.accept();
Client c = new Client(s);
new Thread(c).start();
//把客户端放进数组里;
lists.add(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

/**
* 1、接收客户端发送过来的消息;
* 2、将客户端发送过来的每条消息再发送给每个客户端;
*/
public class Client implements Runnable {

private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bconnect = false;

//取得输入,输出流;
private Client(Socket s) {
this.s = s;
try {
System.out.println("a client connected!");
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bconnect = true;
} catch (IOException e) {
e.printStackTrace();
}
}

//将客户端发过来的消息转发给每一个客户端;
public void send(String str) {
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e) {
lists.remove(this);
System.out.println("a client quit!");
}
}

public void run() {
try {
while (bconnect) {
String str = dis.readUTF();//是阻塞式的
System.out.println(str);
for (int i = 0; i < lists.size(); i++) {
Client c = lists.get(i);
c.send(str);
}
/*// Iterator有锁的概念;
for(Iterator<Client> it = lists.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
Iterator<Client> it = lists.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
} catch (EOFException e) {
System.out.println("Client to close!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
if (dis != null) {
dis.close();
}
if (s != null) {
s.close();
}
} catch (SocketException e) {
System.out.println("System exit!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值