java聊天室代码百度云 java聊天程序代码( 七 )


this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
java多人聊天一般都是怎么搭建的?Java多人聊天可以使用Java的Socket编程实现,主要的思路是:使用服务器来维护所有客户端的连接,并将客户端之间的聊天信息进行转发 。
具体的实现步骤如下:
创建服务器端:使用ServerSocket类创建一个服务器端,并监听指定的端口,等待客户端的连接 。
创建客户端:使用Socket类创建一个客户端,并连接到服务器端 。
实现聊天功能:客户端和服务器端之间可以通过输入和输出流进行通信 , 客户端将聊天信息发送给服务器,服务器再将其转发给其他客户端 。
处理异常:在实现聊天功能时,需要注意处理可能出现的异常,例如连接异常、输入输出异常等等 。
一个简单的Java多人聊天程序的代码框架如下:
服务器端:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
private ServerSocket serverSocket;
private ArrayListClientHandler clients;
public ChatServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
clients = new ArrayListClientHandler();
System.out.println("服务器已启动,等待客户端连接...");
}
public void start() throws IOException {
while (true) {
Socket socket = serverSocket.accept();
ClientHandler client = new ClientHandler(socket, this);
clients.add(client);
client.start();
}
}
public void broadcast(String message) {
for (ClientHandler client : clients) {
client.sendMessage(message);
}
}
public void removeClient(ClientHandler client) {
clients.remove(client);
}
public static void main(String[] args) throws IOException {
ChatServer server = new ChatServer(12345);
server.start();
}
}
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatClient {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
private String name;
public ChatClient(String serverAddress, int port, String name) throws IOException {

推荐阅读