//聊天室的客户端
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatClient extends Applet{
protected boolean loggedIn;//登入状态
protected Frame cp;//聊天室框架
protected static int PORTNUM=7777; //缺省端口号7777
protected int port;//实际端口号
protected Socket sock;
protected BufferedReader is;//用于从sock读取数据的BufferedReader
protected PrintWriter pw;//用于向sock写入数据的PrintWriter
protected TextField tf;//用于输入的TextField
protected TextArea ta;//用于显示对话的TextArea
protected Button lib;//登入按钮
protected Button lob;//登出的按钮
final static String TITLE ="Chatroom applet>>>>>>>>>>>>>>>>>>>>>>>>";
protected String paintMessage;//发表的消息
public ChatParameter Chat;
public void init(){
paintMessage="正在生成聊天窗口";
repaint();
cp=new Frame(TITLE);
cp.setLayout(new BorderLayout());
String portNum=getParameter("port");//呢个参数勿太明
port=PORTNUM;
if (portNum!=null) //书上是portNum==null,十分有问题
port=Integer.parseInt(portNum);
//CGI
ta=new TextArea(14,80);
ta.setEditable(false);//read only attribute
ta.setFont(new Font("Monospaced",Font.PLAIN,11));
cp.add(BorderLayout.NORTH,ta);
Panel p=new Panel();
Button b;
//for login button
p.add(lib=new Button("Login"));
lib.setEnabled(true);
lib.requestFocus();
lib.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
login();
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus();//将键盘输入锁定再右边的文本框中
}
});
//for logout button
p.add(lob=new Button ("Logout"));
lob.setEnabled(false);
lob.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
logout();
lib.setEnabled(true);
lob.setEnabled(false);
lib.requestFocus();
}
});
p.add(new Label ("输入消息:"));
tf=new TextField(40);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(loggedIn){
//pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野来?
int j=tf.getText().indexOf(":");
if(j>0) pw.println(Chat.CMD_MESG+tf.getText());
else
pw.println(Chat.CMD_BCAST+tf.getText());
tf.setText("");//勿使用flush()?
}
}
});
p.add(tf);
cp.add(BorderLayout.SOUTH,p);
cp.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
//如果执行了setVisible或者dispose,关闭窗口
ChatClient.this.cp.setVisible(false);
ChatClient.this.cp.dispose();
logout();
}
});
cp.pack();//勿明白有咩用?
//将Frame cp放在中间
Dimension us=cp.getSize(),
them=Toolkit.getDefaultToolkit().getScreenSize();
int newX=(them.width-us.width)/2;
int newY=(them.height-us.height)/2;
cp.setLocation(newX,newY);
cp.setVisible(true);
paintMessage="Window should now be visible";
repaint();
}
//登录聊天室
public void login(){
if(loggedIn) return;
try{
sock=new Socket(getCodeBase().getHost(),port);
is=new BufferedReader(new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter(sock.getOutputStream(),true);
}catch(IOException e){
showStatus("Can't get socket: "+e);
cp.add(new Label("Can't get socket: "+e));
return;}
//构造并且启动读入器,从服务器读取数据,输出到文本框中
//这里,长成一个线程来避免锁住资源(lockups)
new Thread (new Runnable(){
public void run(){
String line;
try{
while(loggedIn &&((line=is.readLine())!=null))
ta.appendText(line+"\n");
}catch(IOException e){
showStatus("我的天啊,掉线了也!!!!");
return;
}
}
}).start();
//假定登录(其实只是打印相关信息,并没有真正登录)
// pw.println(Chat.CMD_LOGIN+"AppletUser");
pw.println(Chat.CMD_LOGIN+"AppletUser");
loggedIn =true;
}
//模仿退出的代码
public void logout(){
if(!loggedIn)
return;
loggedIn=false;
try{
if(sock!=null)
sock.close();
}catch(IOException ign){
// 异常处理哦
}
}
//没有设置stop的方法,即使从浏览器跳到另外一个网页的时候
//聊天程序还可以继续运行
public void paint(Graphics g){
Dimension d=getSize();
int h=d.height;
int w=d.width;
g.fillRect(0,0,w,2);
g.setColor(Color.black);
g.drawString(paintMessage,10,(h/2)-5);
}
}
聊天室服务器端
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer{
//聊天室管理员ID
protected final static String CHATMASTER_ID="ChatMaster";
//系统信息的分隔符
protected final static String SEP=": ";
//服务器的Socket
protected ServerSocket servSock;
//当前客户端列表
protected ArrayList clients;
//调试标记
protected boolean DEBUG=false;
public ChatParameter Chat;
//主方法构造一个ChatServer,没有返回值
public static void main(String[] argv){
System.out.println("Chat server0.1 starting>>>>>>>>>>>>>>>>");
ChatServer w=new ChatServer();
w.runServer();
System.out.println("***ERROR*** Chat server0.1 quitting");
}
//构造和运行一个聊天服务
ChatServer(){
Chat=new ChatParameter();
clients=new ArrayList();
try{
servSock=new ServerSocket(7777);//实有问题拉,不过可能是他自己定义既一个class.
System.out.println("Chat Server0.1 listening on port:"+7777);
}catch(Exception e){
log("IO Exception in ChatServer.<init>");
System.exit(0);
}
}
public void runServer(){
try{
while(true){
Socket us=servSock.accept();
String hostName=us.getInetAddress().getHostName();
System.out.println("Accpeted from "+hostName);
//一个处理的线程
ChatHandler cl=new ChatHandler(us,hostName);
synchronized(clients){
clients.add(cl);
cl.start();
if(clients.size()==1)
cl.send(CHATMASTER_ID,"Welcome!You are the first one here");
else{
cl.send(CHATMASTER_ID,"Welcome!You are the latest of"+
clients.size()+" users.");
}
}
}
}catch(Exception e){
log("IO Exception in runServer:"+e);
System.exit(0);
}
}
protected void log(String s){
System.out.println(s);
}
//处理会话的内部的类
protected class ChatHandler extends Thread {
//客户端scoket
protected Socket clientSock;
//读取socket的BufferedReader
protected BufferedReader is ;
//在socket 上发送信息行的PrintWriter
protected PrintWriter pw;
//客户端出主机
protected String clientIP;
//句柄
protected String login;
public ChatHandler (Socket sock,String clnt)throws IOException {
clientSock=sock;
clientIP=clnt;
is=new BufferedReader(
new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter (sock.getOutputStream(),true);
}
//每一个ChatHandler是一个线程,下面的是他的run()方法
//用于处理会话
public void run(){
String line;
try{
while((line=is.readLine())!=null){
char c=line.charAt(0);//我顶你老母啊 ,果只Chat.CMD咩xx冇定义 扑啊///!!!
line=line.substring(1);
switch(c){
//case Chat.CMD_LOGIN:
case 'l':
if(!Chat.isValidLoginName(line)){
send(CHATMASTER_ID,"LOGIN"+line+"invalid");
log("LOGIN INVALID from:"+clientIP);
continue;
}
login=line;
broadcast(CHATMASTER_ID,login+" joins us,for a total of"+
clients.size()+" users");
break;
// case Chat.CMD_MESG:
case 'm':
if(login==null){
send(CHATMASTER_ID,"please login first");
continue;
}
int where =line.indexOf(Chat.SEPARATOR);
String recip=line.substring(0,where);
String mesg=line.substring (where+1);
log("MESG: "+login+"--->"+recip+": "+mesg);
ChatHandler cl=lookup(recip);
if(cl==null)
psend(CHATMASTER_ID,recip+"not logged in.");
else
cl.psend(login,mesg);
break;
//case Chat.CMD_QUIT:
case 'q':
broadcast(CHATMASTER_ID,"Goodbye to "+login+"@"+clientIP);
close();
return;//ChatHandler结束
// case Chat.CMD_BCAST:
case 'b':
if(login!=null)
broadcast(login,line);
else
log("B<L FROM"+clientIP);
break;
default:
log("Unknow cmd"+c+"from"+login+"@"+clientIP);
}
}
}catch(IOException e){
log("IO Exception :"+e);
}finally{
//sock 结束,我们完成了
//还不能发送再见的消息
//得有简单的基于命令的协议才行
System.out.println(login+SEP+"All Done");
synchronized(clients){
clients.remove(this);
if(clients.size()==0){
System.out.println(CHATMASTER_ID+SEP+
"I'm so lonely I could cry>>>>>");
}else if(clients.size()==1){
ChatHandler last=(ChatHandler)clients.get(0);
last.send(CHATMASTER_ID,"Hey,you are talking to yourself again");
}
else{
broadcast(CHATMASTER_ID,"There are now"+clients.size()+" users");
}
}
}
}
protected void close(){
if(clientSock==null){
log("close when not open");
return;
}
try{
clientSock.close();
clientSock=null;
}catch(IOException e){
log("Failure ring close to "+clientIP);
}
}
//发送一条消息给用户
public void send(String sender,String mesg){
pw.println(sender+SEP+"*>"+mesg);
}
//发送私有的消息
protected void psend(String sender ,String msg){
send("<*"+sender+"*>",msg);
}
//发送一条消息给所有的用户
public void broadcast (String sender,String mesg){
System.out.println("Broadcasting"+sender+SEP+mesg);
for(int i=0;i<clients.size();i++){
ChatHandler sib=(ChatHandler)clients.get(i);
if(DEBUG)
System.out.println("Sending to"+sib);
sib.send(sender,mesg);
}
if(DEBUG) System.out.println("Done broadcast");
}
protected ChatHandler lookup(String nick){
synchronized(clients){
for(int i=0;i<clients.size();i++){
ChatHandler cl=(ChatHandler)clients.get(i);
if(cl.login.equals(nick))
return cl;
}
}
return null;
}
//将ChatHandler对象转换成一个字符串
public String toString(){
return "ChatHandler["+login+"]";
}
}
}
public class ChatParameter {
public static final char CMD_BCAST='b';
public static final char CMD_LOGIN='l';
public static final char CMD_MESG='m';
public static final char CMD_QUIT='q';
public static final char SEPARATOR=':';//?????
public static final int PORTNUM=7777;
public boolean isValidLoginName(String line){
if (line.equals("CHATMASTER_ID"))
return false;
return true;
}
public void main(String[] argv){
}
}
以上代码由于界面限制的原因 可能有点儿乱
把它整个复制出去 重新整理修改一下就行了
『贰』 求用Java编写的聊天室界面
jsp的
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>欢乐聊天室</title>
</head>
<body>
<%--首先取出用户提交的代号名称,保存在变量chatid中--%>
<%
String chatid = new String();
chatid = request.getParameter("inputid");
%>
<%--使用变量flag来标记用户输入是否合法,如果合法,则flag为true --%>
<%
boolean flag;
flag = true;
if(chatid == null){
chatid = "";
}
if(chatid.length() == 0){
flag = false;
}
%>
<%--比较用户所输入的id和目前聊天室中存在的所有id --%>
<%
for(int i=1; i<=6 && flag; i++){
String itemp = new String();
itemp = itemp.valueOf(i);
int num;
String numtemp = new String();
String temp = new String();
temp = "room" + itemp + "usernum";
numtemp = (String)application.getAttribute(temp);
if(numtemp == null){
numtemp = "0";
application.setAttribute(temp ,numtemp);
}
num = Integer.parseInt(numtemp);
for(int j=1; j<=num && flag; j++){
String jtemp = new String();
jtemp = jtemp.valueOf(j);
%>
<%--从application对象中取出第i个聊天室中第j个用户的id,temp变量保存的是application对象用于保存第i个聊天室中第j个用户的id相应的变量名 --%>
<%
temp = "room" + itemp + "user" + jtemp;
String usertemp = new String();
usertemp = (String)application.getAttribute(temp);
if(usertemp.equalsIgnoreCase(chatid)){
flag = false;
}
}
}
int nnn[] = new int[6];
if(flag){
String temproom = new String();
temproom = (String)session.getValue("chatroom");
if(temproom == null){
session.putValue("chatid",chatid);
}
for(int i=1; i<=6; i++) {
String itemp = new String();
itemp = itemp.valueOf(i);
int num;
String numtemp = new String();
String temp = new String();
temp = "room" + itemp + "usernum";
numtemp = (String)application.getAttribute(temp);
if(numtemp == null){
numtemp = "0";
}
num = Integer.parseInt(numtemp);
nnn[i-1] = num;
}
}
%>
<p align="center"><b><font face="隶书" size="6" color="#FF00FF">欢乐聊天室</font></b></p>
<%
if(flag){
%>
<p align="center"><font color="red"><%=chatid %></font>您好,请选择感兴趣的聊天室!</p>
<center><table border="1" width="370">
<tr>
<td width="50%"><a href="JSPchat.jsp?chatroom=1">今天我们相识(<%=nnn[0]%>)</a></td>
<td width="50%"><a href="JSPchat.jsp?chatroom=2">校园的那条小路(<%=nnn[1]%>)</a></td>
</tr>
<tr>
<td width="50%"><a href="JSPchat.jsp?chatroom=3">职场淘金(<%=nnn[2]%>)</a></td>
<td width="50%"><a href="JSPchat.jsp?chatroom=4">网络技术交流(<%=nnn[3]%>)</a></td>
</tr>
<tr>
<td width="50%"><a href="JSPchat.jsp?chatroom=5">世界体育大看台(<%=nnn[4]%>)</a></td>
<td width="50%"><a href="JSPchat.jsp?chatroom=6">新闻背后的故事(<%=nnn[5]%>)</a></td>
</tr>
</table><center>
<%
}else {
%>
<center><p>id不能为空,或者此id已经被使用,请重新选择!</p><center>
<p><center><a href="login.html">返回</a><center></p>
<%
}
%>
</body>
</html>
『叁』 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聊天室代码加详细注释,并说明设计思路。好的加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); //可显示的。
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;
}
}
}
}
『伍』 急需一个用java 语言写的聊天程序
客户端:
package chatroom;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class client extends JFrame implements ActionListener,Runnable{
JPanel conn,text,send;
JLabel name,sendto;
JComboBox list;
JButton con,snd,clear;
JTextArea talk;
JTextField who,say;
JScrollPane jsp;
Socket client;
InputStream is;
OutputStream os;
PrintStream ps;
BufferedReader br;
String receive,yousay;
Thread th;
DataInputStream dis;
Double tof;
client()
{
super("聊天室客户端");
this.setSize(800,600);
this.setResizable(false);
conn=new JPanel();
text=new JPanel();
send=new JPanel();
this.getContentPane().add(conn);
conn.setBounds(0, 0, this.getWidth(),50);
name=new JLabel("姓名:");
who=new JTextField();
con=new JButton("连接");
conn.setLayout(null);
conn.add(name);
name.setBounds(30, 10, 50, 25);
conn.add(who);
who.setBounds(80, 10, 150, 25);
conn.add(con);
con.setBounds(250,10, 60, 25);
this.getContentPane().add(text);
text.setBounds(0,50,this.getWidth(),450);
text.setLayout(new BorderLayout());
jsp=new JScrollPane();
talk=new JTextArea();
jsp.getViewport().setView(talk);
text.add(jsp,"Center");
talk.setLineWrap(true);
this.getContentPane().add(send);
send.setLayout(null);
send.setBounds(0, 480, this.getWidth(), 150);
sendto=new JLabel("发送到:");
snd=new JButton("发送");
list=new JComboBox();
say=new JTextField();
clear=new JButton("清空");
send.add(sendto);
sendto.setBounds(30, 525, 50, 25);
send.add(list);
list.setBounds(100, 525, 75, 25);
send.add(say);
say.setEditable(true);
say.setBounds(200, 525, 300, 25);
send.add(snd);
snd.setBounds(520, 525, 100, 25);
send.add(clear);
clear.setBounds(650, 525, 100, 25);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
con.addActionListener(this);
snd.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("连接"))
{
try
{
client=new Socket(InetAddress.getLocalHost(),55555);
talk.append("连接成功...\n");
con.setText("断开");
is=client.getInputStream();
os=client.getOutputStream();
th=new Thread(this);
String id=who.getText();
byte b[]=id.getBytes();
DataOutputStream dos=new DataOutputStream(os);
int len=b.length;
dos.writeInt(len);
dos.write(b);
th.start();
}catch(Exception e){talk.append("连接失败\n"+e.toString()+"0000");}
}
else if(ae.getSource()==snd)
{
if(list.getSelectedItem().toString()=="所有人")
{
yousay="@open"+say.getText();
byte b[]=yousay.getBytes();
DataOutputStream dos=new DataOutputStream(os);
try{
int len=b.length;
dos.writeInt(len);
dos.write(b);
}catch(Exception e)
{
System.out.print(e.toString()+"1111");
}
}
else
{
yousay="@whisper"+say.getText();
byte b[]=yousay.getBytes();
byte w[]=list.getSelectedItem().toString().getBytes();
DataOutputStream dos=new DataOutputStream(os);
try{
int len=b.length;
int wlen=w.length;
dos.writeInt(len); //内容
dos.write(b);
dos.writeInt(wlen); //发送对象
dos.write(w);
}catch(Exception e)
{
System.out.print(e.toString()+"AAAA");
}
}
}
else if(ae.getActionCommand().equals("断开"))
{
try
{
client.close();
talk.append("连接已断开\n");
con.setText("连接");
}catch(Exception e){System.out.println(e.toString()+"2222");}
}
}
public void run()
{
while(true)
{
try
{
dis=new DataInputStream(is);
tof=dis.readDouble();
if(tof==1.1)
{
dis=new DataInputStream(is);
int number;
list.removeAllItems();
list.addItem("所有人");
number=dis.readInt();
for(int i=0;i<number;i++)
{
int len=dis.readInt();
byte b[]=new byte[len];
dis.read(b);
String name=new String(b);
list.addItem(name);
}
}
else if(tof==2.2)
{
try
{
dis=new DataInputStream(is);
int len=dis.readInt();
byte b[]=new byte[len];
dis.read(b);
receive=new String(b);
talk.append(receive+"\n");
}catch(Exception e){JOptionPane.showMessageDialog(this, "连接已断开","消息",JOptionPane.INFORMATION_MESSAGE);break;}
}
}catch(Exception e){JOptionPane.showMessageDialog(this, "连接已断开","消息",JOptionPane.INFORMATION_MESSAGE);break;}
}
}
public static void main(String[] args) {
client cl=new client();
}
}
服务端:
package chatroom;
import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.util.Vector;
import java.io.*;
public class server extends JFrame implements Runnable{
JPanel jp1;
JTextArea jta;
JScrollPane jsp;
Socket socket=null;
ServerSocket server;
InputStream is;
OutputStream os;
static int i=0,login;
int no;
static String s="";
Thread sr;
Thread th[]=new Thread[20];
static Vector ol=new Vector();
static public byte w[]=null;
static String from=""; //人名
static String to="";
static String fromtext=""; //内容
static String totext="";
server()
{
super("聊天室服务端");
this.getContentPane().setLayout(new GridLayout(1,1));
this.setSize(400,300);
jp1=new JPanel();
jta=new JTextArea();
jsp=new JScrollPane();
this.getContentPane().add(jp1);
jp1.setLayout(new GridLayout(1,1));
jsp.getViewport().setView(jta);
jp1.add(jsp);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
server sr=new server();
sr.sr=new Thread(sr);
sr.sr.start();
sendtoall sta=new sendtoall();
returnfrom rf=new returnfrom(sr);
returnto rt=new returnto(sr);
sta.start();
rf.start();
rt.start();
}
public void run()
{
try
{
server=new ServerSocket(55555);
while(true)
{
socket=server.accept();
is=socket.getInputStream();
DataInputStream dis=new DataInputStream(is);
int len=dis.readInt();
byte b[]=new byte[len];
dis.read(b);
String id=new String(b);
record v=new record(id,socket);
ol.addElement(v);
for (int i=0;i<ol.size();i++)
{
if (ol.elementAt(i).equals(v))
{
no=i;
}
}
login=1;
s=id+"已来到聊天室!";
th[no]=new Thread(new receive(this,no));
th[no].start();
}
}catch(Exception e){System.out.println(e.toString()+"aaaa");}
}
}
class receive implements Runnable
{
InputStream is;
OutputStream os;
server sr;
Socket sk;
int i;
String name;
String ip;
receive(server sr,int i)
{
this.sr=sr;
this.i=i;
sk=((record)sr.ol.elementAt(i)).ip;
name=((record)sr.ol.elementAt(i)).name;
ip=((record)sr.ol.elementAt(i)).ip.getInetAddress().toString();
}
public void run()
{
while(true)
{
try
{
is=sk.getInputStream();
DataInputStream dis=new DataInputStream(is);
int len=dis.readInt();
byte b[]=new byte[len];
dis.read(b);
String abc=new String(b);
sr.jta.append(abc);
if(abc.substring(0,5).equals("@open"))
{
server.s=name+"["+ip.substring(1, ip.length())+"]"+"说:"+abc.substring(5,abc.length());
sr.jta.append(server.s+"\n");
}
else if(abc.substring(0,8).equals("@whisper"))
{
int wlen=dis.readInt();
sr.w=new byte[wlen];
dis.read(sr.w);
server.to=new String(sr.w);
server.from=((record)sr.ol.elementAt(i)).name;
String ip=((record)sr.ol.elementAt(i)).ip.getInetAddress().toString();
// server.s=server.from+"对"+server.to+"["+ip.substring(1, ip.length())+"]"+"悄悄地说:"+abc.substring(8,abc.length());
server.fromtext="你对"+server.to+"["+ip.substring(1, ip.length())+"]"+"悄悄地说:"+abc.substring(8,abc.length());
server.totext=server.from+"["+ip.substring(1, ip.length())+"]"+"对你悄悄地说:"+abc.substring(8,abc.length());
sr.jta.append(server.s+"\n");
}
}catch(Exception e)
{
try
{
DataOutputStream dos=new DataOutputStream(os);
server.ol.removeElementAt(i);
server.s=name+"已离开聊天室.";
server.login=1;
break;
}catch(Exception f){}
}
}
}
}
class sendtoall extends Thread
{
int len,number;
byte b[];
server sr;
Socket st;
OutputStream os;
DataOutputStream dos;
public void run()
{
while(true)
{
try
{
if(server.login==1)
{
number=0;
number=server.ol.size();
dos=new DataOutputStream(os);
for(int i=0;i<server.ol.size();i++)
{
st=((record)sr.ol.elementAt(i)).ip;
os=st.getOutputStream();
dos=new DataOutputStream(os);
dos.writeDouble(1.1);
dos.writeInt(number);
for (int j=0;j<number;j++)
{
String name=((record)sr.ol.elementAt(j)).name;
byte b[]=name.getBytes();
int len=b.length;
dos.writeInt(len);
dos.write(b);
}
}
server.login=0;
}
else if(!server.s.equals("")&&sr.ol.size()>0)
{
b=server.s.getBytes(); //String类型中 汉字占一个字节,但是byte类型中,汉字占两个字节
len=b.length;
//len=server.s.length();
//b=new byte[len];
//b=server.s.getBytes();
for(int i=0;i<server.ol.size();i++)
{
st=((record)sr.ol.elementAt(i)).ip;
os=st.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
dos.writeDouble(2.2);
dos.writeInt(len);
dos.write(b);
}
server.s="";
}
}catch(Exception e){System.out.println(e.toString()+"sdasd");}
}
}
}
class returnfrom extends Thread
{
int len,wlen;
byte b[];
byte w[];
server sr;
Socket st;
OutputStream os;
DataOutputStream dos;
//String from="",to="";
returnfrom(server sr)
{
this.sr=sr;
}
public void run()
{
while(true)
{
if(!server.fromtext.equals(""))
{
b=server.fromtext.getBytes();
len=b.length;
sr.jta.append(sr.fromtext);
try
{
for(int i=0;i<server.ol.size();i++)
{
if(((record)sr.ol.elementAt(i)).name.equals(server.from))
{
st=((record)sr.ol.elementAt(i)).ip;
os=st.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
dos.writeDouble(2.2);
dos.writeInt(len);
dos.write(b);
}
}
}catch(Exception e){System.out.println(e.toString()+"wwww");}
server.fromtext="";
server.from="";
}
}
}
}
class returnto extends Thread
{
int len,wlen;
byte b[];
byte w[];
server sr;
Socket st;
OutputStream os;
DataOutputStream dos;
//String from="",to="";
returnto (server sr)
{
this.sr=sr;
}
public void run()
{
while(true)
{
if(!server.totext.equals(""))
{
w=server.totext.getBytes();
wlen=w.length;
try
{
for(int i=0;i<server.ol.size();i++)
{
if(((record)sr.ol.elementAt(i)).name.equals(server.to))
{
st=((record)sr.ol.elementAt(i)).ip;
os=st.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
dos.writeDouble(2.2);
dos.writeInt(wlen);
dos.write(w);
}
}
}catch(Exception e){System.out.println(e.toString()+"wwww");}
server.totext="";
server.to="";
}
}
}
}
class record
{
String name;
Socket ip;
record(String id,Socket socket)
{
name=id;
ip=socket;
}
}
以前学习java时写的,是个在线聊天室只有群聊,私聊,上下线提示,搞不好里面还有错误- -其他功能自己看着加吧,你要的功能实在是很好很强大.
『陆』 我做java的简易聊天室,已经可以群聊和私聊,如何把创建房间加进去,且只能同一个房间里才能群聊和私聊
我说下思路:
1、客户端创建房间时给每个房间分配惟一的一个房间ID,房间是公开的,每个连接的客户端都可以看到,房间属性,比如密码,比如黑名单,房间保存在Server内存当中,如果你使用了集群,建议存储到分布式缓存当中(Redis是最好的选择,其次是memcached),当创建完成后,将房间信息发送给所有客户端。新客户端连接进来时,客户端要主动从服务端拉取房间信息。建议采用服务端主动通知(房间增减,服务端主动通知给所有客户端)和客户端定时轮询(客户端起个定时任务,每隔一定时间主动向服务端拉取房间列表)的方式来保证房间列表的动态更新。
2、当客户端选择加入房间时,如果设置有加入条件,比如密码,那就提示客户端输入,如果是其他条件就判断加入客户端是否符合这个条件。服务端保存房间同客户端的关联关系(可以设计成一对多,也就是一个客户端只能在一个房间聊天,也可以设计成多对多,一个客户端可以同时加入多个房间聊天,主要看设计),并将这个消息通知给这个房间所有的客户端列表“欢迎***进入房间”(消息的发送者为系统,房间ID这个房间的ID,接收人无,表示是这个房间的公开消息,消息内容即:欢迎***进入房间。)
3、把聊天内容当成消息的话,那消息应该有这样的属性,发送人,房间ID(如果没有房间ID就当成系统公告消息,在所有房间显示),接收人(如果没有指定接收人,则是公开消息,如果有接收人,就是私聊消息,只能在同一个房间私聊,那在发消息的时候要判断下接收客户端的是否在这个房间列表当中)。
4、再来说消息路由设置,当客户端发送消息时,根据房间ID,找到这个这个房间内所有的客户端列表,如果没有指定接收人,那消息就推送给这个房间关联的所有客户端,如果指定有接收人,接收人不在这个房间,直接提示“***已经离开”,如果还在就把消息推送给这个指定的客户端。
5、房间的管理:踢人,把这个客户端从房间同客户端关联关系解除,并在房间显示消息“***被踢出房间”等等