java socket 多线程 聊天,简单的聊天程序(java的socket+多线程)

本文介绍了如何使用Java实现服务器端的ServerSocket与客户端的Socket进行通信,展示了创建ServerSocket监听连接、处理并发客户端、发送接收消息以及客户端聊天应用的完整过程。通过实例代码,读者可以了解服务器端编程的基本原理和实践技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务端

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

public class ServerTest {

//创建一个ServerSocket,用于监听客户端Socket连接请求

ServerSocket server = null;

//装多个客户端的容器

Collection clients = new ArrayList();

public ServerTest(int port) throws Exception {

server = new ServerSocket(port);

}

//可接受多个客户端连接

public void startServer() throws Exception {

System.out.println("服务器启动中...");

while (true) {

//侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞

Socket s = server.accept();

clients.add(new ClientProcess(s));

System.out.println("NewClient" + s.getInetAddress() + ":" + s.getPort());

System.out.println("ClientCount: " + clients.size() + "\n");

}

}

class ClientProcess implements Runnable {

Socket s = null;

public ClientProcess(Socket s) {

this.s = s;

//启动线程

(new Thread(this)).start();

}

//发送消息给客户端

public void send(String str) throws IOException {

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

dos.writeUTF(str);

}

//获取客户端发来的消息

//public String getMessage() throws Exception {

//DataInputStream dis = new DataInputStream(s.getInputStream());

//String str = dis.readUTF();

//return str;

//}

//释放socket并移除断开的客户端

public void destory() {

try {

if (s != null) s.close();

clients.remove(this);

System.out.println("A client out!");

System.out.println("ClientCount: " + clients.size() + "\n");

} catch (Exception e) {

e.printStackTrace();

}

}

@Override

//继续监听是否有消息发来

public void run() {

try {

DataInputStream dis = new DataInputStream(s.getInputStream());

String str = null;

while (true) {

//没收到消息来该方法会阻塞

str = dis.readUTF();

System.out.println(s.getInetAddress() + "-" + s.getPort() + ": " + str);

//消息共享到多个客户端

for (Iterator it = clients.iterator(); it.hasNext();) {

ClientProcess cp = (ClientProcess) it.next();

if (this != cp) {

cp.send(s.getInetAddress() + "-" + s.getPort() + ": " + str);

}

}

}

} catch (Exception e) {

//客户端退出后触发

System.out.println("Client quit");

this.destory();

}

}

}

public static void main(String[] args) throws Exception {

ServerTest st = new ServerTest(8888);

st.startServer();

}

}

客户端

import java.io.*;

import java.net.*;

import java.awt.*;

import java.awt.event.*;

public class ChatClient extends Frame {

TextArea ta = new TextArea();

TextField tf = new TextField();

Socket s = null;

public void launchFrame() throws Exception {

this.add(ta, BorderLayout.CENTER);

this.add(tf, BorderLayout.SOUTH);

tf.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

try {

String sSend = tf.getText();

if (sSend.trim().length() == 0) {

System.out.println("输入为空!");

return;

}

ChatClient.this.send(sSend);

tf.setText("");

ta.append("me: " + sSend + "\n");

} catch (Exception e) {

e.printStackTrace();

}

}

}

);

this.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

}

);

setBounds(300,300,300,400);

setVisible(true);

ta.requestFocus();

}

public ChatClient() throws Exception {

s = new Socket("39.108.12.42", 9050);

launchFrame();

(new Thread(new ReceiveThread())).start();

}

//向服務器發送數據

public void send(String str) throws Exception {

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

dos.writeUTF(str);

}

public void disconnect() throws Exception {

s.close();

}

class ReceiveThread implements Runnable {

public void run() {

if (s == null) return;

try {

DataInputStream dis = new DataInputStream(s.getInputStream());

String str = dis.readUTF();

while (str != null && str.length() != 0) {

//System.out.println(str);

ChatClient.this.ta.append(str + "\n");

str = dis.readUTF();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

public static void main(String[] args) throws Exception {

ChatClient cc = new ChatClient();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值