Java 实现聊天室可以分为以下几个步骤:
创新互联公司是一家以成都网站建设公司、网页设计、品牌设计、软件运维、seo优化、小程序App开发等移动开发为一体互联网公司。已累计为木制凉亭等众行业中小客户提供优质的互联网建站和软件开发服务。
建立服务器端
首先需要建立一个服务器端,负责接收客户端的连接请求并处理客户端发送过来的消息。
建立客户端
然后需要建立客户端,客户端通过网络连接到服务器端,并向服务器端发送消息。
实现通信协议
为了实现聊天室功能,需要定义一个通信协议,规定客户端和服务器端之间的通信格式,例如消息的头部和内容等。
实现多线程处理
聊天室通常会有多个用户同时在线,因此需要使用多线程来处理多个客户端的连接请求和消息传递。
实现GUI界面(可选)
为了方便用户使用,可以实现一个GUI界面,让用户可以方便地发送和接收消息。
以下是一个简单的 Java 聊天室的代码示例:
java
Copy code
// 服务器端代码
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ServerThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ServerThread(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String msg;
while ((msg = reader.readLine()) != null) {
// 处理客户端发送过来的消息
System.out.println("接收到消息:" + msg);
// 将消息发送给所有客户端
for (Socket s : ServerThreadList.getList()) {
if (s != socket) {
PrintWriter w = new PrintWriter(s.getOutputStream());
w.println(msg);
w.flush();
}
}
}
// 关闭连接
socket.close();
ServerThreadList.removeThread(this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThreadList {
private static List
list = new ArrayList();
public static void addThread(ServerThread thread) {
list.add(thread);
}
public static void removeThread(ServerThread thread) {
list.remove(thread);
}
public static List
getList() {
return list;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
new Thread(new ClientThread(socket)).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while (true) {
String msg = reader.readLine();
writer.println(msg);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader reader;
public ClientThread(Socket socket) {
this.socket = socket;
try {
reader
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;//引入包。
public class ChatClient {
public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.receive();
}
JTextField jtf; // 文本条
JTextArea jta; //文本域。
Socket s; //客户端
PrintWriter out; //输出流
BufferedReader in; //输入流
public ChatClient() {
JFrame frame = new JFrame("ChatClient");//窗口
frame.setSize(400, 300); //大小
jta = new JTextArea(); //文本域
jta.setEditable(false); //不可编辑
jtf = new JTextField();//文件条
jtf.addActionListener(new ActionListener() { //添加监听。
public void actionPerformed(ActionEvent arg0) {
send(); //调用send()方法
}
});
frame.getContentPane().add(new JScrollPane(jta)); //添加滚动条
frame.getContentPane().add(jtf, "South"); //添加文本条
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口。
frame.setVisible(true); //可显示的。
try {
s = new Socket("127.0.0.1", 9000); //连接服务端 socket("主机名",端口号);
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //建立输入流
out = new PrintWriter(s.getOutputStream());//输出流
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive() { //接受服务端发来别的客户端的信息。
while (true) {
try {
String text = in.readLine(); //读一行
this.jta.append(text + "\n"); //jta 添加上读入的。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
public void send() { //发送消息
String text = this.jtf.getText(); //得到你输入的消息
this.jtf.setText(""); //在文本域中显示你输入的消息。
out.println(text); //打印出。
out.flush(); //清空
}
}
Server端
import java.net.*;
import java.io.*;
import java.util.*;//引入包
public class ChatServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9000); //建立服务端,端口号为9000
List list = new ArrayList(); //创建个List集合。
while (true) {
Socket s = ss.accept(); //等待客户端的请求。
list.add(s); //把每一个client都add到集合中去。
Thread t = new ServerThread(s, list); //线程。
t.start(); //启动。
}
}
}
class ServerThread extends Thread {
Socket s;
List list;
BufferedReader in;
PrintWriter out;
public ServerThread(Socket s, List list) { //构造。传入socket和list。
this.s = s;
this.list = list;
try {
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //输入流
out = new PrintWriter(s.getOutputStream()); //输出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() { //必须实现其run()方法。
while (true) {
try {
String str = in.readLine(); //得到client端的message。
if (str == null) //如果没有消息就返回。
return;
Iterator it = list.iterator(); //遍历list。
while (it.hasNext()) { //如果list有下一个
Socket socket = (Socket) (it.next()); //因为list中都是存的socket
PrintWriter o = new PrintWriter(socket.getOutputStream()); //输出流
o.println(str); //输出
o.flush(); //清空
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return;
}
}
}
}
【ClientSocketDemo.java 客户端Java源代码】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//声明客户端Socket对象socket
Socket socket = null;
//声明客户器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明字符串数组对象response,用于存储从服务器接收到的信息
String response[];
//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745
public ClientSocketDemo()
{
try
{
//创建客户端socket,服务器地址取本地,端口号为10745
socket = new Socket("localhost",10745);
//创建客户端数据输入输出流,用于对服务器端发送或接收数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//获取客户端地址及端口号
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服务器发送数据
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//从服务器接收数据
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745
public ClientSocketDemo(String hostname)
{
try
{
//创建客户端socket,hostname参数指定服务器地址,端口号为10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有两个个参数时的构造方法,第一个参数hostname指定服务器地址
//第一个参数serverPort指定服务器端口号
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服务器端Java源代码】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//声明ServerSocket类对象
ServerSocket serverSocket;
//声明并初始化服务器端监听端口号常量
public static final int PORT = 10745;
//声明服务器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息
InetAddress ip = null;
//声明字符串数组对象request,用于存储从客户端发送来的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串数组
try
{
//获取本地服务器地址信息
ip = InetAddress.getLocalHost();
//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接
serverSocket = new ServerSocket(PORT);
//创建Socket类的对象socket,用于保存连接到服务器的客户端socket对象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//创建服务器端数据输入输出流,用于对客户端接收或发送数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客户端发送来的数据信息,并显示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客户端发送数据
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}