标签:
Client:
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ChatClient extends Frame {
private static final long serialVersionUID = 1L;
private Socket socket;// 声明socket对象
private TextArea textArea = new TextArea();// 实例化文本域
private TextField textField = new TextField();// 实例化文本框
private DataOutputStream dos;// 输出字节流
private DataInputStream dis;// 输入字节流
private boolean isConnected;// 标记位,代表是否已经连接上
Thread thread = new Thread(new RecvThread());// 实例化接收其他客户端发送的消息线程
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);// 设置位置
setSize(500, 500);// 设置大小
add(textArea, BorderLayout.NORTH);
add(textField, BorderLayout.SOUTH);
pack();// 组件自适应窗口
addWindowListener(new WindowAdapter() {// 添加窗口监听器,使用匿名类的方式实现
@Override
public void windowClosing(WindowEvent e) {
disConnect();// 关闭连接
System.exit(0);// 退出
}
});
textField.addActionListener(new TFListener());// 为文本框注册监听事件
setVisible(true);
connect();
thread.start();// 启动线程
}
public void connect() {
try {
socket = new Socket("127.0.0.1", 64444);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
isConnected = socket.isConnected();
System.out.print("LocalAddress->" + socket.getLocalAddress() + ",LocalPort" + socket.getLocalPort());
System.out.println("succeed connected!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// TextField的监听器类
private class TFListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String content = textField.getText().trim();
String text = textArea.getText();
if (!"".equals(text))
text += "\n";
text += content;// 将内容重新拼接,主要是取出之前的内容,添加textField中的内容,然后重新显示
textArea.setText(text);
textField.setText("");// 将textField文本框置空
try {
dos.writeUTF(content);// 向服务器端输出信息
dos.flush();// 刷新缓冲区
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void disConnect() {
try {
if (dos != null)
dos.close();
if (socket != null)
socket.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while (isConnected) {
String str = dis.readUTF();
textArea.setText(textArea.getText() + str + "\n");
}
} catch (SocketException e) {
System.out.println("Good bye!" + e.getMessage());
} catch (EOFException e) {
System.out.println("Good bye - bye!" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
}
Server:
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.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
static ServerSocket serverSocket;
boolean isStarted = false;// 标志是否启动
List<Client> clients = new ArrayList<ChatServer.Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
serverSocket = new ServerSocket(64444);// 在固定的端口上进行监听
isStarted = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
while (isStarted) {
Socket s = serverSocket.accept();// 接受连接请求
SocketAddress remoteSocketAddress = s.getRemoteSocketAddress();
System.out.println(remoteSocketAddress.toString());
System.out.println("a client connected!");
Client c = new Client(s);// 启动一个线程
new Thread(c).start();
clients.add(c);// 加入客户端集合,以便将消息群发给每一个客户端
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (serverSocket != null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket socket;
private boolean connected = false;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
public Client(Socket s) {
this.socket = s;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
connected = socket.isConnected();
System.out.println("connected = " + connected);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String content = null;
try {
Client client = null;
while (connected) {
try {
content = dataInputStream.readUTF();
System.out.println(content);
System.out.println("clients.size()=>" + clients.size());
for (int i = 0; i < clients.size(); i++) {
client = clients.get(i);
// 分别向每一个客户端发消息
if (client != this)
client.dataOutputStream.writeUTF(content);
}
} catch (EOFException e) {
clients.remove(client);// 将客户端移出集合
System.out.println(e.getMessage());
System.out.println("Client closed!");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (dataInputStream != null)
dataInputStream.close();
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
标签:
原文地址:http://blog.csdn.net/shijiebei2009/article/details/44758873