JAVA聊天室 客户端 和 服务器 完整代码
CS模式的QQ这是服务器:ChatServerjavaimport javanet;
import javaio;
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();
apprun();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
Systemoutprintln("服务器已经建立!");
while(numbers<10)
{
Socket theSocket=theServeraccept();
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;i<numbers-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)
{
Systemoutprintln("发布信息:"+line);
for(int i=0;i<=numbers-1;i++)
chatters[i]sendMessage(line);
}
}====================================================这是客户端:ChatClientjavaimport javaawt;
import javaawtevent;
import javaxswing;
import javanet;
import javaio;
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("聊天室");
framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cccreateComponents();
framegetContentPane()add(content);
framesetSize(550,310);
framesetVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
messagesetEditable(false);
JPanel paneMsg=new JPanel();
paneMsgsetBorder(BorderFactorycreateTitledBorder("聊天内容"));
paneMsgadd(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanelsetBorder(BorderFactorycreateTitledBorder("在线用户:"));
listPaneladd(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnectsetEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPaneladd(new Label("服务器IP:"));
buttonPaneladd(ipField);
buttonPaneladd(new Label("端口:"));buttonPaneladd(portField);
buttonPaneladd(new Label("用户名:"));
buttonPaneladd(IDField);
buttonPaneladd(connect);
buttonPaneladd(disconnect);
paneadd(messageField,"South");
paneadd(buttonPanel,"North");
paneadd(paneMsg,"Center");
paneadd(listPanel,"West");
connectaddActionListener(this);
disconnectaddActionListener(this);
messageFieldaddActionListener(this);
IDFieldaddActionListener(this);
ipFieldaddActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(egetSource()==connect){
user=IDFieldgetText();
String ip=ipFieldgetText();
int port =IntegerparseInt(portFieldgetText());
if(!userequals("")&&connectToServer(ip,port,user))
{
disconnectsetEnabled(true);
connectsetEnabled(false);
}
}
if(egetSource()==disconnect)disconnectFromServer();
if(egetSource()==messageField)
if(theSocket!=null)
{
outprintln("MESSAGE:"+messageFieldgetText());
messageFieldsetText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
outprintln("LEAVE:"+user);
disconnectsetEnabled(false);
connectsetEnabled(true);
thread=null;
theSocketclose();
}catch(IOException io){}
theSocket=null;
messagesetText("");
userssetText("");
}
}
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(theSocketgetInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocketgetOutputStream()),true);
outprintln("USER:"+user);
messagesetText("");
connected=true;
thread=new Thread(this);
threadstart();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
Systemoutprintln(line);
Message messageline;
messageline=new Message(line);
if(messagelineisValid())
{
if(messagelinegetType()equals("JOIN"))
{
user=messagelinegetBody();
messageappend(user+"进入了聊天室\n");
}
else if(messagelinegetType()equals("LIST"))
updateList(messagelinegetBody());
else if(messagelinegetType()equals("MESSAGE"))
messageappend(messagelinegetBody()+"\n");
else if(messagelinegetType()equals("REMOVE"))
messageappend(messagelinegetBody()+"离开了聊天室\n");
}
else
messageappend("出现问题:"+line+"\n");
}
public void updateList(String line)
{
userssetText("");
String str=line;
for(int i=0;i<10;i++)
userList[i]="";
int index=strindexOf(":");
int a=0;
while(index!=-1){
userList[a]=strsubstring(0,index);
str=strsubstring(index+1);
a++;
index=strindexOf(":");
}
for(int i=0;i<10;i++)
usersappend(userList[i]+"\n");
}
public void run(){
try{
String line="";
while(connected && line!=null){
line=inreadLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import javanet;
import javaio;
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;
thisparent=parent;
in=new BufferedReader(new InputStreamReader(theSocketgetInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocketgetOutputStream()),true);
thePort=theSocketgetPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
outprintln(line);
}
public void setupUserName(String setname){
user=setname;
//Systemoutprint(user+"参加");
parentbroadcastMessage("JOIN:"+user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messagelineisValid()){
if(messagelinegetType()equals("USER")){
setupUserName(messagelinegetBody());
parentbroadcastMessage("LIST:"+parentreturnUsernameList());
}
else if(messagelinegetType()equals("MESSAGE")){
parentbroadcastMessage("MESSAGE:"+user+"说: "+messagelinegetBody());
}
else if(messagelinegetType()equals("LEAVE")){
String c=disconnectClient();
parentbroadcastMessage("REMOVE:"+c);
parentbroadcastMessage("LIST:"+parentreturnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
inclose();
outclose();
theSocketclose();
parentremoveConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=inreadLine())!=null){
Systemoutprintln("收到:"+line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Messagejavapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLineindexOf(":");
if(pos>=0){
type=messageLinesubstring(0,pos)toUpperCase();
body=messageLinesubstring(pos+1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
thistype=type;
thisbody=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件,先运行服务段端。。。 这是我以前学的时候写过的!希望能帮的上你
不是电脑问题,是网络或者服务器本身的问题,我也经常这样,
如果那你网络不快,下个迅游加速器试试,如果能最好关了360,
如果你自身的网络没有问题,那就是服务器的问题,TX的服务器是真心不给力,
我诺克萨斯经常卡,偶尔进不去,换区就好了,
我只知道j2me的网络连接看起来即时的东西都是作假的,因为在j2me里服务器端要主动找寻客户端的话难度太大,至少在没有客户端的IP或者任何能标识客户端的东西都没有。
说到这里你也应该明白了吧~ 并不只是单靠API就可以完成一个商业软件的,就像你这个问题,完全可以在客户端做一个循环,刷服务器端,每1秒发送给服务器端本机在线确认信息,或者每几秒发送一次,然后在服务器端也做一个等待验证,如果3分钟或者1分钟或者更短的时间内接收不到该用户所登录的客户端发送过来的在线确认信息,而且也没有收到正常退出信息,那就一定是非正常退出咯~ 总结就是客户端刷服务器端~
或者你厉害的话,就再做一个进程,当你这个程序启动时调用另一个监听该程序的进程,但要用JAVA做到这一步就很麻烦了。
类似聊天室的即时通讯,用JAVA做肯定是需要一个服务器端超时机制的,这个机制也肯定需要客户端定时发送在线确认的,就这么简单。
0条评论