java聊天室代码免费 java聊天程序代码

java实现聊天室是怎么做到的?Java 实现聊天室可以分为以下几个步骤:
建立服务器端
首先需要建立一个服务器端 , 负责接收客户端的连接请求并处理客户端发送过来的消息 。
建立客户端
然后需要建立客户端,客户端通过网络连接到服务器端,并向服务器端发送消息 。
实现通信协议
为了实现聊天室功能 , 需要定义一个通信协议,规定客户端和服务器端之间的通信格式,例如消息的头部和内容等 。
实现多线程处理
聊天室通常会有多个用户同时在线,因此需要使用多线程来处理多个客户端的连接请求和消息传递 。
实现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);
}
【java聊天室代码免费 java聊天程序代码】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
急求JavaC/S聊天室代码,有界面,可发消息传文件,非常感谢客户端:importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.GridLayout;importjava.awt.Toolkit;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.util.HashMap;importjava.util.Map;importjava.util.StringTokenizer;importjavax.swing.DefaultListModel;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JList;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.JSplitPane;importjavax.swing.JTextArea;importjavax.swing.JTextField;importjavax.swing.border.TitledBorder;publicclassClient{privateJFrameframe;privateJListuserList;privateJTextAreatextArea;privateJTextFieldtextField;privateJTextFieldtxt_port;privateJTextFieldtxt_hostIp;privateJTextFieldtxt_name;privateJButtonbtn_start;privateJButtonbtn_stop;privateJButtonbtn_send;privateJPanelnorthPanel;privateJPanelsouthPanel;privateJScrollPanerightScroll;privateJScrollPaneleftScroll;privateJSplitPanecenterSplit;privateDefaultListModellistModel;privatebooleanisConnected=false;privateSocketsocket;privatePrintWriterwriter;privateBufferedReaderreader;privateMessageThreadmessageThread;//负责接收消息的线程privateMaponLineUsers=newHashMap();//所有在线用户//主方法,程序入口publicstaticvoidmain(String[]args){newClient();}//执行发送publicvoidsend(){if(!isConnected){JOptionPane.showMessageDialog(frame,"还没有连接服务器,无法发送消息!","错误",JOptionPane.ERROR_MESSAGE);return;}Stringmessage=textField.getText().trim();if(message==null||message.equals("")){JOptionPane.showMessageDialog(frame,"消息不能为空!","错误",JOptionPane.ERROR_MESSAGE);return;}sendMessage(frame.getTitle()+"@"+"ALL"+"@"+message);textField.setText(null);}//构造方法publicClient(){textArea=newJTextArea();textArea.setEditable(false);textArea.setForeground(Color.blue);textField=newJTextField();txt_port=newJTextField("719");txt_hostIp=newJTextField("127.0.0.1");txt_name=newJTextField("Lei");btn_start=newJButton("连接");btn_stop=newJButton("断开");btn_send=newJButton("发送");listModel=newDefaultListModel();userList=newJList(listModel);northPanel=newJPanel();northPanel.setLayout(newGridLayout(1,7));northPanel.add(newJLabel("端口"));northPanel.add(txt_port);northPanel.add(newJLabel("服务器IP"));northPanel.add(txt_hostIp);northPanel.add(newJLabel("姓名"));northPanel.add(txt_name);northPanel.add(btn_start);northPanel.add(btn_stop);northPanel.setBorder(newTitledBorder("连接信息"));rightScroll=newJScrollPane(textArea);rightScroll.setBorder(newTitledBorder("消息显示区"));leftScroll=newJScrollPane(userList);leftScroll.setBorder(newTitledBorder("在线用户"));southPanel=newJPanel(newBorderLayout());southPanel.add(textField,"Center");southPanel.add(btn_send,"East");southPanel.setBorder(newTitledBorder("写消息"));centerSplit=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftScroll,rightScroll);centerSplit.setDividerLocation(100);frame=newJFrame("客户机");//更改JFrame的图标://frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));frame.setLayout(newBorderLayout());frame.add(northPanel,"North");frame.add(centerSplit,"Center");frame.add(southPanel,"South");frame.setSize(600,400);intscreen_width=Toolkit.getDefaultToolkit().getScreenSize().width;intscreen_height=Toolkit.getDefaultToolkit().getScreenSize().height;frame.setLocation((screen_width-frame.getWidth())/2,(screen_height-frame.getHeight())/2);frame.setVisible(true);//写消息的文本框中按回车键时事件textField.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){send();}});//单击发送按钮时事件btn_send.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){send();}});//单击连接按钮时事件btn_start.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){intport;if(isConnected){JOptionPane.showMessageDialog(frame,"已处于连接上状态,不要重复连接!","错误",JOptionPane.ERROR_MESSAGE);return;}try{try{port=Integer.parseInt(txt_port.getText().trim());}catch(NumberFormatExceptione2){thrownewException("端口号不符合要求!端口为整数!");}StringhostIp=txt_hostIp.getText().trim();Stringname=txt_name.getText().trim();if(name.equals("")||hostIp.equals("")){thrownewException("姓名、服务器IP不能为空!");}booleanflag=connectServer(port,hostIp,name);if(flag==false){thrownewException("与服务器连接失败!");}frame.setTitle(name);JOptionPane.showMessageDialog(frame,"成功连接!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);}}});//单击断开按钮时事件btn_stop.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){if(!isConnected){JOptionPane.showMessageDialog(frame,"已处于断开状态,不要重复断开!","错误",JOptionPane.ERROR_MESSAGE);return;}try{booleanflag=closeConnection();//断开连接if(flag==false){thrownewException("断开连接发生异常!");}JOptionPane.showMessageDialog(frame,"成功断开!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);}}});//关闭窗口时事件frame.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){if(isConnected){closeConnection();//关闭连接}System.exit(0);//退出程序}});}/***连接服务器**@paramport*@paramhostIp*@paramname*/publicbooleanconnectServer(intport,StringhostIp,Stringname){//连接服务器try{socket=newSocket(hostIp,port);//根据端口号和服务器ip建立连接writer=newPrintWriter(socket.getOutputStream());reader=newBufferedReader(newInputStreamReader(socket.getInputStream()));//发送客户端用户基本信息(用户名和ip地址)sendMessage(name+"@"+socket.getLocalAddress().toString());//开启接收消息的线程messageThread=newMessageThread(reader,textArea);messageThread.start();isConnected=true;//已经连接上了returntrue;}catch(Exceptione){textArea.append("与端口号为:"+port+"IP地址为:"+hostIp+"的服务器连接失败!"+"\r\n");isConnected=false;//未连接上returnfalse;}}/***发送消息**@parammessage*/publicvoidsendMessage(Stringmessage){writer.println(message);writer.flush();}/***客户端主动关闭连接*/@SuppressWarnings("deprecation")publicsynchronizedbooleancloseConnection(){try{sendMessage("CLOSE");//发送断开连接命令给服务器messageThread.stop();//停止接受消息线程//释放资源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;returntrue;}catch(IOExceptione1){e1.printStackTrace();isConnected=true;returnfalse;}}//不断接收消息的线程classMessageThreadextendsThread{privateBufferedReaderreader;privateJTextAreatextArea;//接收消息线程的构造方法publicMessageThread(BufferedReaderreader,JTextAreatextArea){this.reader=reader;this.textArea=textArea;}//被动的关闭连接publicsynchronizedvoidcloseCon()throwsException{//清空用户列表listModel.removeAllElements();//被动的关闭连接释放资源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;//修改状态为断开}publicvoidrun(){Stringmessage="";while(true){try{message=reader.readLine();StringTokenizerstringTokenizer=newStringTokenizer(message,"/@");Stringcommand=stringTokenizer.nextToken();//命令if(command.equals("CLOSE"))//服务器已关闭命令{textArea.append("服务器已关闭!\r\n");closeCon();//被动的关闭连接return;//结束线程}elseif(command.equals("ADD")){//有用户上线更新在线列表Stringusername="";StringuserIp="";if((username=stringTokenizer.nextToken())!=null(userIp=stringTokenizer.nextToken())!=null){Useruser=newUser(username,userIp);onLineUsers.put(username,user);listModel.addElement(username);}}elseif(command.equals("DELETE")){//有用户下线更新在线列表Stringusername=stringTokenizer.nextToken();Useruser=(User)onLineUsers.get(username);onLineUsers.remove(user);listModel.removeElement(username);}elseif(command.equals("USERLIST")){//加载在线用户列表intsize=Integer.parseInt(stringTokenizer.nextToken());Stringusername=null;StringuserIp=null;for(inti=0;i

推荐阅读