聊天系统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);
}
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
急求一个JAVA编写的局域网聊天代码?不要求很复杂 。只要可以在两台机子上简单的对话就可以 。//以下引入包
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.applet.*;
public class regit extends JApplet implements ActionListener,ItemListener//接口
{
String s=null;
//对象的声明
JLabel labelname,labelpass,labelsxe,labeladdress,labelmail,labelphone;//标签
JTextField textname,textaddress,textmail,textphone;//文本框
JRadioButton r1,r2;//单选按纽
ButtonGroup bg;//组
JPasswordField textpass;//密码域
JButton buttonregit,buttonreset;//注册按纽 重写按纽
JPanel p;//面板
String sex;//定义性别字符串
URL url;//统一资源定位
BufferedWriter out1,out2;//流
BufferedReader in;
//布局方式
GridBagLayout gbl;
GridBagConstraints gc;
AppletContext co;//接口
//初始化
public void init()
{
//new 对象
labelname=new JLabel("用 户 名:");
labelpass=new JLabel("用户密码:");
labelsxe=new JLabel("性别:");
labeladdress=new JLabel("地址:");
labelmail=new JLabel("电子邮件:");
labelphone=new JLabel("联系电话:");
textname=new JTextField(15); textname.setForeground(Color.red);
textname.setToolTipText("请在这输入你的用户名");
textaddress=new JTextField(15);textaddress.setForeground(Color.red);
textaddress.setToolTipText("请在这输入你的地址");
textmail=new JTextField(15); textmail.setForeground(Color.red);
textmail.setToolTipText("请在这里输入你的E-mail地址");
textphone=new JTextField(15); textphone.setForeground(Color.red);
textphone.setToolTipText("请在这输入你的电话号码");
r1=new JRadioButton("男"); r1.setBackground(new Color(47,177,210));//设置颜色
r2=new JRadioButton("女"); r2.setBackground(new Color(47,177,210));//设置颜色
bg=new ButtonGroup();
bg.add(r1);bg.add(r2);//加入组,实现单选
textpass=new JPasswordField(15);
textpass.setToolTipText("在这里输入密码");
textpass.setForeground(Color.red);
buttonregit=new JButton("注册"); buttonregit.setBackground(new Color(47,177,210));//设置颜色
buttonregit.setToolTipText("点击按纽完成注册");
buttonreset=new JButton("填写"); buttonreset.setBackground(new Color(47,177,210));//设置颜色
buttonreset.setToolTipText("点击按纽刷新重写");
gbl=new GridBagLayout(); ///////////////////////////////////////
gc=new GridBagConstraints(); //////采用GridBagLayout布局方式////////
p=new JPanel();
p.setLayout(gbl);
p.setBackground(new Color(47,177,210));
this.getContentPane().add(p);//加入面板
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=2;
gbl.setConstraints(labelname,gc);
p.add(labelname);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=2;
gbl.setConstraints(textname,gc);
p.add(textname);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=4;
gbl.setConstraints(labelpass,gc);
p.add(labelpass);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=4;
gbl.setConstraints(textpass,gc);
p.add(textpass);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=6;
gbl.setConstraints(labelsxe,gc);
p.add(labelsxe);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=6;
gbl.setConstraints(r1,gc);
p.add(r1);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=5;
gc.gridy=6;
gbl.setConstraints(r2,gc);
p.add(r2);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=8;
gbl.setConstraints(labeladdress,gc);
p.add(labeladdress);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=8;
gbl.setConstraints(textaddress,gc);
p.add(textaddress);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=10;
gbl.setConstraints(labelmail,gc);
p.add(labelmail);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=10;
gbl.setConstraints(textmail,gc);
p.add(textmail);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=12;
gbl.setConstraints(labelphone,gc);
p.add(labelphone);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=12;
gbl.setConstraints(textphone,gc);
p.add(textphone);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=16;
gbl.setConstraints(buttonregit,gc);
p.add(buttonregit);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=16;
gbl.setConstraints(buttonreset,gc);
p.add(buttonreset);
/////////////////////////////////////////////
co=this.getAppletContext();
/////////////////////////////////////////////
buttonregit.addActionListener(this);//按纽事件的监听
buttonreset.addActionListener(this);//按纽事件的监听
r1.addItemListener(this);//选择事件的监听
r2.addItemListener(this);//选择事件的监听
textphone.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
//注册按纽事件
if(e.getSource()==buttonregit)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定义字符串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判断注册资料 信息 是否为空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"资料不能为空,请重新注册聊天系统Java代码!","【温馨提示】",error);
return;//弹出对话框并返回
}
try//写入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷离视线聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用户名已经存在,请更换名字!");
textname.setText("");//设置为空,重新输入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代码判断是否有同名
{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\message.txt",true));
}//创建文件
catch(Exception ee)
{}
try
{
out1.write(s1 "#" s2);//写
out1.newLine();
out2.write("用户名聊天系统Java代码:" s1);
out2.newLine();
out2.write("密码:" s2);
out2.newLine();
out2.write("性别:" sex);
out2.newLine();
out2.write("地址:" s3);
out2.newLine();
out2.write("电子邮件:" s4);
out2.newLine();
out2.write("电话:" s5);
out2.newLine();
out1.flush();
out2.flush();//清理缓冲
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注册成功!");
try
{
String qss="";
url=new url(/qss);//连接上网址
co.showDocument(url);
}
catch(Exception exx)
{}
}
}
//////////////////////以下为回车事件
if(e.getSource()==textphone)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定义字符串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判断注册资料 信息 是否为空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"资料不能为空 , 请重新注册!","【温馨提示】",error);
return;//弹出对话框并返回
}
try//写入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷离视线聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用户名已经存在,请更换名字!");
textname.setText("");//设置为空 , 重新输入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代码判断是否有同名
{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\message.txt",true));
}//创建文件
catch(Exception ee)
{}
try
{
out1.write(s1 "#" s2);//写
out1.newLine();
out2.write("用户名:" s1 "密码:" s2 "性别:" sex "地址:" s3 "电子邮件:" s4 "电话:" s5);//写
out2.newLine();
out1.flush();
out2.flush();//清理缓冲
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注册成功!");
try
{
String qss="";
url=new url(/qss);//连接上网址
co.showDocument(url);
}
catch(Exception exx)
{}
}
}
if(e.getSource()==buttonreset)//刷新重写事件
{
textname.setText("");
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
}
}
//////////////////////////////////////////
//
public void itemStateChanged(ItemEvent ex)
{
if(ex.getSource()==r1)
{
sex=new String("男");
}
else if(ex.getSource()==r2)
{
sex=new String("女");
}
}
}
参考资料:试试看,刚在网上找的
JAVA聊天室 客户端 和 服务器 完整代码CS模式的QQ这是服务器:ChatServer.javaimport java.net.*;
import java.io.*;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
app.run();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
System.out.println("服务器已经建立!");
while(numbers10)
{
Socket theSocket=theServer.accept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i=numbers-1;i)
if(chatters[i]==c)index=i;
for(int i=index;inumbers-1;i)
chatters[i]=chatters[i 1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i=numbers-1;i)
line=line chatters[i].user ":";
return line;
}
public void broadcastMessage(String line)
{
System.out.println("发布信息:" line);
for(int i=0;i=numbers-1;i)
chatters[i].sendMessage(line);
}
}====================================================这是客户端:ChatClient.javaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cc.createComponents();
frame.getContentPane().add(content);
frame.setSize(550,310);
frame.setVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
message.setEditable(false);
JPanel paneMsg=new JPanel();
paneMsg.setBorder(BorderFactory.createTitledBorder("聊天内容"));
paneMsg.add(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanel.setBorder(BorderFactory.createTitledBorder("在线用户:"));
listPanel.add(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnect.setEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPanel.add(new Label("服务器IP:"));
buttonPanel.add(ipField);
buttonPanel.add(new Label("端口:"));buttonPanel.add(portField);
buttonPanel.add(new Label("用户名:"));
buttonPanel.add(IDField);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
pane.add(messageField,"South");
pane.add(buttonPanel,"North");
pane.add(paneMsg,"Center");
pane.add(listPanel,"West");
connect.addActionListener(this);
disconnect.addActionListener(this);
messageField.addActionListener(this);
IDField.addActionListener(this);
ipField.addActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==connect){
user=IDField.getText();
String ip=ipField.getText();
int port =Integer.parseInt(portField.getText());
if(!user.equals("")connectToServer(ip,port,user))
{
disconnect.setEnabled(true);
connect.setEnabled(false);
}
}
if(e.getSource()==disconnect)disconnectFromServer();
if(e.getSource()==messageField)
if(theSocket!=null)
{
out.println("MESSAGE:" messageField.getText());
messageField.setText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
out.println("LEAVE:" user);
disconnect.setEnabled(false);
connect.setEnabled(true);
thread=null;
theSocket.close();
}catch(IOException io){}
theSocket=null;
message.setText("");
users.setText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
out.println("USER:" user);
message.setText("");
connected=true;
thread=new Thread(this);
thread.start();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
System.out.println(line);
Message messageline;
messageline=new Message(line);
if(messageline.isValid())
{
if(messageline.getType().equals("JOIN"))
{
user=messageline.getBody();
message.append(user "进入了聊天室\n");
}
else if(messageline.getType().equals("LIST"))
updateList(messageline.getBody());
else if(messageline.getType().equals("MESSAGE"))
message.append(messageline.getBody() "\n");
else if(messageline.getType().equals("REMOVE"))
message.append(messageline.getBody() "离开了聊天室\n");
}
else
message.append("出现问题:" line "\n");
}
public void updateList(String line)
{
users.setText("");
String str=line;
for(int i=0;i10;i)
userList[i]="";
int index=str.indexOf(":");
int a=0;
while(index!=-1){
userList[a]=str.substring(0,index);
str=str.substring(index 1);
a;
index=str.indexOf(":");
}
for(int i=0;i10;i)
users.append(userList[i] "\n");
}
public void run(){
try{
String line="";
while(connectedline!=null){
line=in.readLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import java.net.*;
import java.io.*;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
this.parent=parent;
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
thePort=theSocket.getPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
out.println(line);
}
public void setupUserName(String setname){
user=setname;
//System.out.print(user "参加");
parent.broadcastMessage("JOIN:" user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messageline.isValid()){
if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:" parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:" user "说: " messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:" c);
parent.broadcastMessage("LIST:" parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:" line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos 1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件,先运行服务段端 。。。这是我以前学的时候写过的!希望能帮的上你
求一个用JAVA写的网络编程的网络聊天系统,能够实现两个人聊天信息收发 。这个是客户端
import java.net.*;
import java.io.*;
import java.awt.*;
【聊天系统Java代码 java聊天室的代码设计思路】import java.awt.event.*;
public class client extends Frame implements ActionListener{
int i=1;Frame f;
TextField ip,port;
Label Lip,Lport;
Button connect,exit;
public static void main(String args[])
{client c1 = new client();
c1.init();
}
public void init()
{
f=new Frame("client connection");
f.setLayout(new FlowLayout());
ip =new TextField("localhost");
port =new TextField("8189",5);
Lip=new Label("ip address");
Lport=new Label("port");
connect=new Button("connect");
exit=new Button("exit");
connect.addActionListener(this);
exit.addActionListener(this);
f.add(Lip);
f.add(ip);
f.add(Lport);
f.add(port);
f.add(connect);
f.add(exit);
f.setSize(500,60);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==exit)
System.exit(0);
if(e.getSource()==connect)
{
new Thread(new threadclient(ip.getText(),port.getText(),i)).start();
i;
}
}
}
class threadclient extends Frame implements Runnable,ActionListener{
String ip,port;
int no;
Frame f;
TextArea ta;
TextArea name;
TextField tf;
Button send,bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
BufferedWriter out;
threadclient(String n,String m,int i)
{
ip=n;
port=m;
no=i;
}
public void run(){
f=new Frame("client NO."no);
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(this);
bye.addActionListener(this);
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
Integer tmp=new Integer(port);
int portint =tmp.intValue();
try
{
s=new Socket(ip,portint);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out1=new PrintStream(s.getOutputStream());
ta.append(in.readLine() "\n");
}catch(Exception e)
{
System.out.println(e.getMessage() " ss");
}
}
public void send(String txt){
try{
out1.println(txt);
out1.flush();
ta.append(in.readLine() "\n");
}catch(IOException e)
{
System.out.println(e.getMessage() "send");
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bye){
send("BYE");
System.exit(0);
}
if (e.getSource()==send)
send(tf.getText());
}
}
这个是服务器
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class server {
private static MapString,Socket clientMap=new HashMapString,Socket();
public static void main(String[] args) {
int i = 1;
try {
ServerSocket s = new ServerSocket(8189);
for (;;) {
Socket incoming = s.accept();
System.out.println("连接成功"i);
ThreadedEchoHandler teh=new ThreadedEchoHandler(incoming, i);
teh.start();
String name=teh.getClientname();
clientMap.put(name,incoming);
i;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ThreadedEchoHandler extends Thread {
Frame f;
TextArea ta;
TextField tf;
Button send, bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
PrintWriter out;
public ThreadedEchoHandler(Socket i, int c) {
incoming = i;
counter = c;
f=new Frame("server");
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send(tf.getText());
}
});
bye.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send("bye");
}
});
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
}
public String getClientname() {
try {
in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
out = new PrintWriter(incoming.getOutputStream(), true);
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage() "get");
}
return null;
}
public void send(String context){
out.println(context);
out.flush();
}
public void run() {
try {
boolean done = false;
while (!done) {
String str = in.readLine();
if (str == null)
done = true;
else {
out.println("Echo("counter"):"str);
ta.append("Echo("counter"):"str "\n");
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (Exception e) {
System.out.println(e.getMessage() "run");
}
}
private Socket incoming;
private int counter;
}
这个鸟东西是个新手写的 。唉,太烂了,我无力吐槽 。
为java聊天室代码加详细注释,并说明设计思路 。好的加100分 。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); //可显示聊天系统Java代码的 。
try {
s = new Socket("127.0.0.1", 9000); //连接服务端 socket("主机名"聊天系统Java代码,端口号);
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() { //接受服务端发来别聊天系统Java代码的客户端的信息 。
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(); //得到聊天系统Java代码你输入的消息
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); //建立服务端聊天系统Java代码 , 端口号为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;
}
}
}
}
关于聊天系统Java代码和java聊天室的代码设计思路的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读