做个聊天室程序练习Socket编程,分享,记录一下
【Java Socket】学习资料:
http://baike.baidu.com/view/1589439.htm
http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html
这样就是一个简单的服务器程序:
// 在9999端口监听连接
ServerSocket serverSocket = new ServerSocket(9999);
// 开始循环
while (true) {
// 等待连接
Socket socket = serverSocket.accept();
// 处理链接的线程类
ServerThread st = new ServerThread(socket);
// 启动线程处理
new Thread(st).start();
}
简单的客户端:// 建立连接
socket = new Socket(“127.0.0.1”, 8888);
// 输入输出流,需要什么流通过 socket.getInputStream(); 自己封装
BufferedReader netIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter netOut = new PrintWriter(socket.getOutputStream());
程序实现图:
server代码:
package com.lyl.chatServer;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
private ServerSocket serverSocket;
private boolean isStart;
// 所有在线的客户端
List<ClientThread> clients = new ArrayList<ClientThread>();
public static void main(String[] args) {
new ChatServer().startService();
}
public void startService() {
try {
serverSocket = new ServerSocket(9999);
isStart = true;
System.out.println("9999端口 等待客户端连接……");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (isStart) {
Socket socket = serverSocket.accept();
ClientThread client = new ClientThread(socket);
new Thread(client).start();
clients.add(client);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/* 处理单个客户端的线程类 */
class ClientThread implements Runnable {
private Socket socket;
private DataInputStream dis;
private DataOutputStream dos;
private boolean isRun;
public ClientThread(Socket s) {
this.socket = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
isRun = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String s) {
try {
dos.writeUTF(s);
System.out.println(s);
} catch (IOException e) {
clients.remove(this);
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (isRun) {
String s = dis.readUTF();
for (int i = 0; i < clients.size(); i++) {
// 对在线的客户端发送消息
ClientThread c = clients.get(i);
c.send(s);
}
}
} catch (EOFException e) {
clients.remove(this);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null)
dis.close();
if (dos != null)
dos.close();
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
完整工程:http://download.csdn.net/detail/lyl_studio/4615877