求java网络聊天室(BS模式)程序代码

求java网络聊天室(BS模式)程序代码,第1张

共四个java文件,源代码如下:
import javaawt;
import javanet;
import javaawtevent;
import javaio;
import javautilHashtable;
public class ChatArea extends Panel implements ActionListener,Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 谈话显示区,私聊显示区=null;
TextField 送出信息=null;
Button 确定,刷新谈话区,刷新私聊区;
Label 提示条=null;
String name=null;
Hashtable listTable;
List listComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Colororange);
thiswidth=width;
thisheight=height;
setSize(width,height);
thislistTable=listTable;
thisname=name;
threadMessage=new Thread(this);
谈话显示区=new TextArea(10,10);
私聊显示区=new TextArea(10,10);
确定=new Button("送出信息到:");
刷新谈话区=new Button("刷新谈话区");
刷新私聊区=new Button("刷新私聊区");
提示条=new Label("双击聊天者可私聊",LabelCENTER);
送出信息=new TextField(28);
确定addActionListener(this);
送出信息addActionListener(this);
刷新谈话区addActionListener(this);
刷新私聊区addActionListener(this);
listComponent=new List();
listComponentaddActionListener(this);
privateChatList=new Choice();
privateChatListadd("大家()");
privateChatListselect(0);

add(谈话显示区);
谈话显示区setBounds(10,10,(width-120)/2,(height-120));
add(私聊显示区);
私聊显示区setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));
add(listComponent);
listComponentsetBounds(10+(width-120),10,100,(height-160));
add(提示条);
提示条setBounds(10+(width-120),10+(height-160),110,40);
Panel pSouth=new Panel();
pSouthadd(送出信息);
pSouthadd(确定);
pSouthadd(privateChatList);
pSouthadd(刷新谈话区);
pSouthadd(刷新私聊区);
add(pSouth);
pSouthsetBounds(10,20+(height-120),width-20,60);

}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
thissocket=socket;
thisin=in;
thisout=out;
try
{
threadMessagestart();
}
catch(Exception e)
{
}
}
public void actionPerformed(ActionEvent e)
{

if(egetSource()==确定||egetSource()==送出信息)
{
String message="";
String people=privateChatListgetSelectedItem();
people=peoplesubstring(0,peopleindexOf("("));
message=送出信息getText();
if(messagelength()>0)
{
try {
if(peopleequals("大家"))
{
outwriteUTF("公共聊天内容:"+name+"说:"+message);
}
else
{
outwriteUTF("私人聊天内容:"+name+"悄悄地说:"+message+"#"+people);
}
}
catch(IOException event)
{
}
}
}
else if(egetSource()==listComponent)
{
privateChatListinsert(listComponentgetSelectedItem(),0);
privateChatListrepaint();
}
else if(egetSource()==刷新谈话区)
{
谈话显示区setText(null);
}
else if(egetSource()==刷新私聊区)
{
私聊显示区setText(null);
}
}
public void run()
{
while(true)
{
String s=null;
try
{
s=inreadUTF();
if(sstartsWith("聊天内容:"))
{
String content=ssubstring(sindexOf(":")+1);
谈话显示区append("\n"+content);
}
if(sstartsWith("私人聊天内容:"))
{
String content=ssubstring(sindexOf(":")+1);
私聊显示区append("\n"+content);
}
else if(sstartsWith("聊天者:"))
{
String people=ssubstring(sindexOf(":")+1,sindexOf("性别"));
String sex=ssubstring(sindexOf("性别")+2);

listTableput(people,people+"("+sex+")");

listComponentadd((String)listTableget(people));
listComponentrepaint();
}
else if(sstartsWith("用户离线:"))
{
String awayPeopleName=ssubstring(sindexOf(":")+1);
listComponentremove((String)listTableget(awayPeopleName));
listComponentrepaint();
谈话显示区append("\n"+(String)listTableget(awayPeopleName)+"离线");
listTableremove(awayPeopleName);
}
Threadsleep(5);
}
catch(IOException e)
{
listComponentremoveAll();
listComponentrepaint();
listTableclear();
谈话显示区setText("和服务器的连接已中断\n必须刷新浏览器才能再次聊天");
break;
}
catch(InterruptedException e)
{
}
}
}
}
ChatServerjava
import javaio;
import javanet;
import javautil;
public class ChatServer
{
public static void main(String args[])
{
ServerSocket server=null;
Socket you=null;
Hashtable peopleList;
peopleList=new Hashtable();
while(true)
{
try
{
server=new ServerSocket(6666);
}
catch(IOException e1)
{
Systemoutprintln("正在监听");
}
try {
you=serveraccept();
InetAddress address=yougetInetAddress();
Systemoutprintln("用户的IP:"+address);

}
catch (IOException e)
{
}
if(you!=null)
{
Server_thread peopleThread=new Server_thread(you,peopleList);
peopleThreadstart();
}
else {
continue;
}
}
}
}
class Server_thread extends Thread
{
String name=null,sex=null;
Socket socket=null;
File file=null;
DataOutputStream out=null;
DataInputStream in=null;
Hashtable peopleList=null;
Server_thread(Socket t,Hashtable list)
{
peopleList=list;
socket=t;
try {
in=new DataInputStream(socketgetInputStream());
out=new DataOutputStream(socketgetOutputStream());
}
catch (IOException e)
{
}
}
public void run()
{

while(true)
{ String s=null;
try
{
s=inreadUTF();
if(sstartsWith("姓名:"))
{
name=ssubstring(sindexOf(":")+1,sindexOf("性别"));
sex=ssubstring(slastIndexOf(":")+1);
boolean boo=peopleListcontainsKey(name);
if(boo==false)
{
peopleListput(name,this);
outwriteUTF("可以聊天:");
Enumeration enum=peopleListelements();
while(enumhasMoreElements())
{
Server_thread th=(Server_thread)enumnextElement();
thoutwriteUTF("聊天者:"+name+"性别"+sex);
if(th!=this)
{
outwriteUTF("聊天者:"+thname+"性别"+thsex);
}
}

}
else
{
outwriteUTF("不可以聊天:");
}
}
else if(sstartsWith("公共聊天内容:"))
{
String message=ssubstring(sindexOf(":")+1);
Enumeration enum=peopleListelements();
while(enumhasMoreElements())
{
((Server_thread)enumnextElement())outwriteUTF("聊天内容:"+message);
}
}

else if(sstartsWith("用户离开:"))
{
Enumeration enum=peopleListelements();
while(enumhasMoreElements())
{ try
{
Server_thread th=(Server_thread)enumnextElement();
if(th!=this&&thisAlive())
{
thoutwriteUTF("用户离线:"+name);
}
}
catch(IOException eee)
{
}
}
peopleListremove(name);
socketclose();
Systemoutprintln(name+"用户离开了");
break;
}
else if(sstartsWith("私人聊天内容:"))
{
String 悄悄话=ssubstring(sindexOf(":")+1,sindexOf("#"));
String toPeople=ssubstring(sindexOf("#")+1);

Server_thread toThread=(Server_thread)peopleListget(toPeople);
if(toThread!=null)
{
toThreadoutwriteUTF("私人聊天内容:"+悄悄话);
}
else
{
outwriteUTF("私人聊天内容:"+toPeople+"已经离线");
}
}
}
catch(IOException ee)
{
Enumeration enum=peopleListelements();
while(enumhasMoreElements())
{ try
{
Server_thread th=(Server_thread)enumnextElement();
if(th!=this&&thisAlive())
{
thoutwriteUTF("用户离线:"+name);
}
}
catch(IOException eee)
{
}
}
peopleListremove(name);
try
{
socketclose();
}
catch(IOException eee)
{
}

Systemoutprintln(name+"用户离开了");
break;
}
}
}
}
import javaawt;
import javaio;
import javanet;
import javaapplet;
import javautilHashtable;
ClientChatjava
public class ClientChat extends Applet implements Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
InputNameTextField 用户提交昵称界面=null;
ChatArea 用户聊天界面=null;
Hashtable listTable;
Label 提示条;
Panel north, center;
Thread thread;
public void init()
{
int width=getSize()width;
int height=getSize()height;
listTable=new Hashtable();
setLayout(new BorderLayout());
用户提交昵称界面=new InputNameTextField(listTable);
int h=用户提交昵称界面getSize()height;
用户聊天界面=new ChatArea("",listTable,width,height-(h+5));
用户聊天界面setVisible(false);
提示条=new Label("正在连接到服务器,请稍等",LabelCENTER);
提示条setForeground(Colorred);
north=new Panel(new FlowLayout(FlowLayoutLEFT));
center=new Panel();
northadd(用户提交昵称界面);
northadd(提示条);
centeradd(用户聊天界面);
add(north,BorderLayoutNORTH);
add(center,BorderLayoutCENTER);
validate();
}
public void start()
{
if(socket!=null&&in!=null&&out!=null)
{ try
{
socketclose();
inclose();
outclose();
用户聊天界面setVisible(false);

}
catch(Exception ee)
{
}
}
try
{
socket = new Socket(thisgetCodeBase()getHost(), 6666);
in=new DataInputStream(socketgetInputStream());
out=new DataOutputStream(socketgetOutputStream());
}
catch (IOException ee)
{
提示条setText("连接失败");
}
if(socket!=null)
{
InetAddress address=socketgetInetAddress();
提示条setText("连接:"+address+"成功");
用户提交昵称界面setSocketConnection(socket,in,out);
northvalidate();
}
if(thread==null)
{
thread=new Thread(this);
threadstart();
}
}

public void stop()
{
try
{
socketclose();
thread=null;
}
catch(IOException e)
{
thisshowStatus(etoString());
}
}
public void run()
{
while(thread!=null)
{
if(用户提交昵称界面get能否聊天()==true)
{
用户聊天界面setVisible(true);
用户聊天界面setName(用户提交昵称界面getName());
用户聊天界面setSocketConnection(socket,in,out);
提示条setText("祝聊天愉快!");
centervalidate();
break;
}
try
{
Threadsleep(100);
}
catch(Exception e)
{
}
}
}
}
InputNameTextField。java
import javaawt;
import javanet;
import javaawtevent;
import javaio;
import javautilHashtable;
public class InputNameTextField extends Panel implements ActionListener,Runnable
{
TextField nameFile=null;
String name=null;
Checkbox male=null,female=null;
CheckboxGroup group=null;
Button 进入聊天室=null,退出聊天室=null;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread=null;
boolean 能否聊天=false;
Hashtable listTable;
public InputNameTextField(Hashtable listTable)
{
thislistTable=listTable;
nameFile=new TextField(10);
group=new CheckboxGroup();
male=new Checkbox("男",true,group);
female=new Checkbox("女",false,group);
进入聊天室=new Button("进入");
退出聊天室=new Button("退出");
进入聊天室addActionListener(this);
退出聊天室addActionListener(this);
thread=new Thread(this);
add(new Label("昵称:"));
add(nameFile);
add(male);
add(female);
add(进入聊天室);
add(退出聊天室);
退出聊天室setEnabled(false);
}
public void set能否聊天(boolean b)
{
能否聊天=b;
}
public boolean get能否聊天()
{
return 能否聊天;
}
public String getName()
{
return name;
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{

thissocket=socket;
thisin=in;
thisout=out;
try{
threadstart();
}
catch(Exception e)
{
nameFilesetText(""+e);
}
}
public Socket getSocket()
{
return socket;
}
public void actionPerformed(ActionEvent e)
{
if(egetSource()==进入聊天室)
{
退出聊天室setEnabled(true);
if(能否聊天==true)
{
nameFilesetText("您正在聊天:"+name);
}
else
{
thissetName(nameFilegetText());
String sex=groupgetSelectedCheckbox()getLabel();
if(socket!=null&&name!=null)
{
try{
outwriteUTF("姓名:"+name+"性别:"+sex);
}
catch(IOException ee)
{
nameFilesetText("没有连通服务器"+ee);
}
}
}
}
if(egetSource()==退出聊天室)
{
try
{
outwriteUTF("用户离开:");
}
catch(IOException ee)
{
}
}
}
public void run()
{
String message=null;
while(true)
{
if(in!=null)
{
try
{
message=inreadUTF();
}
catch(IOException e)
{
nameFilesetText("和服务器断开"+e);
}
}
if(messagestartsWith("可以聊天:"))
{
能否聊天=true;
break;
}
else if(messagestartsWith("聊天者:"))
{
String people=messagesubstring(messageindexOf(":")+1);
listTableput(people,people);
}
else if(messagestartsWith("不可以聊天:"))
{
能否聊天=false;
nameFilesetText("该昵称已被占用");
}
}
}
}

自定义一个线程类或者一个Runnable类。。
并定义一个socket类型的属性。。
构造方法接受一个socket类型的参数。。对socket属性用他来初始化。。
然后这个地方。。
Client=serveraccept( );
Thread thread=new Thread(Client);//把获得的客户端socket穿进去。。
threadstart();
然后在你自定义的线程或者Runnable类里面的run方法写上你想用那个socket做的事就行了。。这样与每个客户端的通信即socket都是一个单独的线程了。。
给你改了下哈。。可能不对哈。。反正你按照那个思路改的话肯定没问题的。。
package java07_25;
import javaawt;
import javaawtevent;
import javaioDataInputStream;
import javaioIOException;
import javaioInputStream;
import javaioOutputStream;
import javanetServerSocket;
import javanetSocket;
public class SocketServer extends Frame implements ActionListener {
Label label = new Label("输入聊天信息,按回车发送!");
TextField tf = new TextField(20);
TextArea ta = new TextArea();
Panel panel = new Panel();
ServerSocket server;
Socket Client;
InputStream DataIn;
OutputStream DataOut;
public SocketServer() {
super("服务器 ");
setSize(380, 300);
paneladd(label);
paneladd(tf);
tfaddActionListener(this);
add("North", panel);
add("Center", ta);
tasetBackground(Colorblack);
tasetForeground(Coloryellow);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Systemexit(0);
}
});
show();
try {
server = new ServerSocket(5000);
while (true) {
Client = serveraccept();
Thread thread = new Thread(new SSocket(Client));
threadstart();
}
} catch (IOException ioe) {
}
}
public static void main(String args[]) {
new SocketServer();
}
public void actionPerformed(ActionEvent e) {
try {
String str = new String(tfgetText());
byte buf[] = strgetBytes();
tfsetText(" ");
DataOutwrite(buf);
taappend("服务器说:" + str + "\n");
} catch (IOException ioe) {
}
}
class SSocket implements Runnable {
Socket client;
public SSocket(Socket client) {
thisclient = client;
}
public void run() {
DataInputStream input;
while (true) {
try {
taappend("已经和客户机连接:" + clientgetInetAddress()
+ clientgetInetAddress()getHostName() + "\n\n");
DataIn = clientgetInputStream();
DataOut = clientgetOutputStream();
byte buff[] = new byte[512];
DataInread(buff);
String str = new String(buff);
taappend("客户机说:" + str + "\n");
} catch (IOException e) {
eprintStackTrace();
}
}
}
}
}

以下是Java中Eclipse中的所有set方法:
1 setActionCommand(String command)
2 setAlignmentX(float alignmentX)
3 setAlignmentY(float alignmentY)
4 setAlwaysOnTop(boolean alwaysOnTop)
5 setBackground(Color bg)
6 setBackgroundAt(int index, Color background)
7 setBounds(int x, int y, int width, int height)
8 setBorder(Border border)
9 setBorderPainted(boolean b)
10 setBounds(Rectangle r)
11 setCancelButtonText(String cancelText)
12 setClickable(boolean clickable)
13 setColumns(int columns)
14 setContentPane(Container contentPane)
15 setCurrentDirectory(File dir)
16 setCursor(Cursor cursor)
17 setDebugGraphicsOptions(int debugOptions)
18 setDefaultButton(JButton defaultButton)
19 setDefaultCloseOperation(int operation)
20 setDefaultLightWeightPopupEnabled(boolean enabled)
21 setDialogTitle(String title)
22 setDirectoryOnly(boolean directoryOnly)
23 setDisabledIcon(Icon disabledIcon)
24 setDisabledSelectedIcon(Icon disabledSelectedIcon)
25 setDividerLocation(int location)
26 setDocument(Document doc)
27 setDoubleBuffered(boolean aFlag)
28 setDragEnabled(boolean b)
29 setEnabled(boolean enabled)
30 setExtendedState(int state)
31 setFileFilter(FileFilter filter)
32 setFocusable(boolean focusable)
33 setFocusCycleRoot(boolean focusCycleRoot)
34 setFocusOwner(Component focusOwner)
35 setFont(Font font)
36 setForeground(Color fg)
37 setForegroundAt(int index, Color foreground)
38 setIcon(Icon icon)
39 setIconAt(int index, Icon icon)
40 setIgnoreRepaint(boolean ignoreRepaint)
41 setIndex(int index)
42 setInputVerifier(InputVerifier inputVerifier)
43 setInsets(Insets insets)
44 setLabelFor(Component labelFor)
45 setLayout(LayoutManager layout)
46 setLightWeightPopupEnabled(boolean aFlag)
47 setLocale(Locale locale)
48 setLookAndFeel(String className)
49 setMaximumSize(Dimension maximumSize)
50 setMinimumSize(Dimension minimumSize)
51 setModel(BoundedRangeModel newModel)
52 setMnemonic(int mnemonic)
53 setModal(boolean modal)
54 setName(String name)
55 setOpaque(boolean isOpaque)
56 setPreferredSize(Dimension preferredSize)
57 setPrompt(String prompt)
58 setProperty(String propertyName, Object value)
59 setResizable(boolean resizable)
60 setSelected(boolean selected)
61 setSelectedIndex(int index)
62 setSelectedTextColor(Color color)
63 setSelectedValue(Object anObject, boolean shouldScroll)
64 setSelectionColor(Color selectionColor)
65 setSelectionEnd(int selectionEnd)
66 setSelectionModel(ListSelectionModel newModel)
67 setSelectionStart(int selectionStart)
68 setSplitterPosition(int position)
69 setStartOffset(int offset)
70 setState(FrameState state)
71 setStepSize(double d)
72 setSubElements(ArrayList<Element> subElements)
73 setTabLayoutPolicy(int policy)
74 setPreferredSize(Dimension preferredSize)
75 setToolTipText(String text)
76 setTransferHandler(TransferHandler newHandler)
77 setUI(ComponentUI newUI)
78 setValue(Object aValue, boolean isSelected)
79 setVisible(boolean b)
80 setViewportView(Component view)
81 setWantsInput(boolean wantsInput)
82 setWrapStyleWord(boolean wrap)
83 setXORMode(boolean state)
84 setYear(int year)
85 setZoom(int zoom)
86 setZOrder(Component comp, int index)
希望可以帮到您的工作。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zz/13430000.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-08-04
下一篇 2023-08-04

发表评论

登录后才能评论

评论列表(0条)

保存