有关java socket(wu1011,longrm请来看下)
我写了个java socket的程序 模仿wu1011,longrm写的聊天室程序目前登录没问题
就是登录完后不能正常运行,不能互相聊天
请知道的朋友帮忙看下代码
Server.java
import java.awt.List;
import
import
import
import
import
import
import
import
import
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.awt.*;
import javax.swing.*;
//import MyRoomServer.ClientThread;
public class Server extends JFrame
{
JTextArea jtaMessage=null,jtaSend=null,jtaSysLog=null;
List userList=null;
JButton jbSend,jbCancel;
Thread thread;
Hashtable userSockets=new Hashtable();
Server()
{
super("聊天服务器");
jtaMessage=new JTextArea(10,60);
JPanel jpNorth=new JPanel();
jpNorth.setLayout(new BorderLayout(10,10));
jpNorth.add(new JLabel("聊天记录"),BorderLayout.NORTH);
JScrollPane jspMessage=new JScrollPane(jtaMessage,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jpNorth.add(jspMessage);
JPanel jpCenter=new JPanel();
jpCenter.setLayout(new BorderLayout(10,10));
JPanel jpleft=new JPanel();
jpleft.setLayout(new BorderLayout(10,10));
JPanel jpright=new JPanel();
jpright.setLayout(new BorderLayout(10,10));
userList=new List(8,false);
JScrollPane jspUserList=new JScrollPane(userList,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jpleft.add(new JLabel("用户列表"),BorderLayout.NORTH);
jpleft.add(jspUserList,BorderLayout.CENTER);
jtaSend=new JTextArea(8,20);
JScrollPane jspSend=new JScrollPane(jtaSend,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel jpDown=new JPanel();
jbSend=new JButton("发送信息");
jbCancel=new JButton("取消发送");
jpDown.add(jbSend);
jpDown.add(jbCancel);
jpright.add(new JLabel("发送服务器消息"),BorderLayout.NORTH);
jpright.add(jspSend,BorderLayout.CENTER);
jpright.add(jpDown,BorderLayout.SOUTH);
jpCenter.add(jpleft,BorderLayout.WEST);
jpCenter.add(jpright,BorderLayout.CENTER);
JPanel jpSouth=new JPanel();
jpSouth.setLayout(new BorderLayout(10,10));
jpSouth.add(new Label("系统日志:"),BorderLayout.NORTH);
jtaSysLog=new JTextArea(8,60);
JScrollPane jspSysLog=new JScrollPane(jtaSysLog,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jpSouth.add(jspSysLog,BorderLayout.CENTER);
this.add(jpNorth,BorderLayout.NORTH);
this.add(jpCenter,BorderLayout.CENTER);
this.add(jpSouth,BorderLayout.SOUTH);
this.pack();
this.setVisible(true);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thread = new Thread()
{
public void run()
{
try
{
ServerSocket serversocket = new ServerSocket(8888);
jtaSysLog.append("服务器启动于:" + Server.getDate() + "\n");
while (true)
{
Socket socket = serversocket.accept();
ClientThread thread = new ClientThread(socket);
thread.start();
// clientNo++;
}
}
catch (IOException ex)
{
System.out.println(ex);
}
}
};
thread.start();
}
public static void main(String args[])
{
new Server();
}
class ClientThread extends Thread
{
DataInputStream dataIn=null;
DataOutputStream dataOut=null;
Socket socket=null;
String inMessage;
String outMessage;
String userName;
ClientThread(){}
ClientThread(Socket socket)
{
this.socket=socket;
}
public void run()
{
try
{
dataOut=new DataOutputStream(socket.getOutputStream());
dataIn=new DataInputStream(socket.getInputStream());
while(true)
{
inMessage=dataIn.readUTF();
if(inMessage.startsWith("userinformation#") )
{
String message[]=inMessage.split("#");//客户信息分解
userName=message[1];
DB db=new DB();
try
{
String logonMessage=db.canLogon(message[1], message[2]);
dataOut.writeUTF(logonMessage);
if(logonMessage.equals("ok"))
{
userSockets.put(userName, socket);
InetAddress inetaddress = socket.getInetAddress();
jtaSysLog.append(message[1] + "的IP地址是:"+ inetaddress.getHostAddress() + "\n");
String temp="系统提示:"+message[1]+"来了";
jtaSysLog.append(Server.getDate()+temp+"\n");
userList.add(message[1]);
sendToAll(temp);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
else if (inMessage.indexOf("对") != -1
&& inMessage.indexOf("公开的说") != -1)
{
sendToAll(inMessage);
jtaMessage.append(Server.getDate() + " " +inMessage + "\n");
}
else if (inMessage.indexOf("对") != -1
&& inMessage.indexOf("悄悄的说") != -1)
{
String toUser=inMessage.substring(userName.length()+1, inMessage.indexOf("悄"));
sendToUser(toUser,inMessage);
jtaMessage.append(Server.getDate()+ " " + inMessage + "\n");
}
else if (inMessage.indexOf("对大家说") != -1)
{
sendToAll(inMessage);
jtaMessage.append(Server.getDate() + " " +inMessage + "\n");
}
}
}
catch (IOException ex)
{
System.out.println("@@@@" + ex);
userSockets.remove(userName);
userList.remove(this.userName);
sendToAll("系统提示:" + this.userName + "下线了");
jtaSysLog.append(Server.getDate()+ " " + "系统提示:" + this.userName
+ "下线了" + "\n");
}
}
public void sendToUser(String message,String name)
{
synchronized (userSockets)
{
try {
Socket s = (Socket)userSockets.get(name);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(message);
}
catch (IOException ie) {
//cs.debug(ie.toString() + "\n");
ie.printStackTrace();
}
}
}
public void sendToAll(String message)
{
synchronized (userSockets)
{
// For each client, get the output stream and send the message
Enumeration e = userSockets.elements();
while( e.hasMoreElements())
{
try
{
DataOutputStream dout = new DataOutputStream(((Socket) e.nextElement()).getOutputStream());
dout.writeUTF(message);
}
catch (IOException ie)
{
ie.printStackTrace();
}
}
}
}
}
public static String getDate()
{
Date date=new Date();
DateFormat dateFormat=DateFormat.getDateTimeInstance();
String time=dateFormat.format(date);
return time;
}
}
Client.java
package qq;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import *;
import *;
import java.text.DateFormat;
import java.util.Date;
public class Client extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JButton jbSend, jbCancel;
JTextArea jtaSend, jtaMessage;// 发送窗口和聊天记录
List userList;
JRadioButton jrbAll, jrbOne;// 聊天模式
//BufferedReader inMessage;
//PrintWriter outMessage;
DataInputStream dataIn;
DataOutputStream dataOut;
Socket socket;
//String serverIP;// 服务器IP
String userName;// 所登录的用户名
String message;// 接受信息
String addName;// 有新用户登录
String removeName;// 有用户离开
Thread thread;
Client(String userName, Socket socket)
{
this.userName=userName;
this.socket=socket;
jbSend=new JButton("发送");
jbCancel=new JButton("取消");
jtaSend=new JTextArea(8,60);
jtaMessage=new JTextArea(10,40);
userList=new List(8,false);
jrbAll=new JRadioButton("群聊");
jrbAll.setSelected(true);
jrbOne=new JRadioButton("私聊");
ButtonGroup group = new ButtonGroup();
group.add(jrbAll);
group.add(jrbOne);
JScrollPane jspSend=new JScrollPane(jtaSend,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JScrollPane jspMessage=new JScrollPane(jtaMessage,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JScrollPane jspList=new JScrollPane(userList,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel jpCenter=new JPanel();
jpCenter.setLayout(new BorderLayout(10,10));
JPanel jpSouth=new JPanel();
jpSouth.setLayout(new BorderLayout(10,10));
JPanel jpLeft=new JPanel();
jpLeft.setLayout(new BorderLayout(10,10));
JPanel jpRight=new JPanel();
jpRight.setLayout(new BorderLayout(10,10));
jpLeft.add(new JLabel("聊天记录"),BorderLayout.NORTH);
jpLeft.add(jspMessage,BorderLayout.CENTER);
jpRight.add(new JLabel("用户列表"),BorderLayout.NORTH);
jpRight.add(jspList,BorderLayout.CENTER);
jpCenter.add(jpLeft,BorderLayout.CENTER);
jpCenter.add(jpRight,BorderLayout.EAST);
JPanel jpUp=new JPanel();
JPanel jpButton=new JPanel();
jpUp.add(new JLabel("聊天模式:"));
jpUp.add(jrbAll);
jpUp.add(jrbOne);
jpButton.add(jbSend);
jpButton.add(jbCancel);
jpSouth.add(jpUp,BorderLayout.NORTH);
jpSouth.add(jspSend,BorderLayout.CENTER);
jpSouth.add(jpButton,BorderLayout.SOUTH);
this.add(jpCenter,BorderLayout.CENTER);
this.add(jpSouth,BorderLayout.SOUTH);
this.setTitle("聊天程序客户端");
this.setVisible(true);
this.pack();
this.setLocation(200, 130);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
dataIn=new DataInputStream(socket.getInputStream());
dataOut=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
thread=new Thread(){
public void run(){
try
{
// dataIn=new DataInputStream(socket.getInputStream());
// dataOut=new DataOutputStream(socket.getOutputStream());
while (true)
{
//message = dataIn.readUTF();
message="系统提示:xx来了";
if (message.indexOf("系统提示:") != -1&& message.indexOf("来了") != -1)
{
addName = message.substring(5, message.indexOf("来"));
userList.add(addName);
}
else if (message.indexOf("系统提示:") != -1
&& message.indexOf("下线了") != -1)
{
userList.remove(removeName);
}
else
jtaMessage.append(Client.getDate() + message + "\n");
}
}
catch (Exception ex)
{
System.out.println("^^^" + ex);
}}};
}
// public static void main(String args[])
// {
// new Client("127.0.0.1", "admin");
// }
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbCancel)
{
jtaSend.setText("");
} else if (e.getSource() == jbSend)
{
String who = "";
if (jrbAll.isSelected())
{
boolean is_public = true;
for (int i = 0; i < userList.getRows(); i++)
{
if (userList.isIndexSelected(i))
{
if (!userList.getItem(i).toString().equals(userName))
{
who = userName.trim() + "对"
+ userList.getSelectedItem() + "公开的说";
is_public = false;
} else
{
// MsgLogjta.append("你不能跟自己发信息!!! " + "\n");
JOptionPane.showMessageDialog(null,
"你不能给自己发信息,请重新选择");
is_public = false;
jtaSend.setText("");
}
}
}
if (is_public)
who = userName.trim() + "对大家说:";
}
// else if (jrbOne.isSelected()
// && !userList.getSelectedItem().toString().equals(userName))
// {
// who = userName.trim() + "对" + userList.getSelectedItem()
// + "悄悄的说";
// }
// else if (jrbOne.isSelected()
// && userList.getSelectedItem().toString().equals(userName))
// {
// who = "";
// // MsgLogjta.append("你不能跟自己发信息!!! " + "\n");
// JOptionPane.showMessageDialog(null, "你不能给自己发信息,请您重新选择");
// jtaSend.setText("");
// }
else if(jrbOne.isSelected())
{
for(int i=0;i<userList.getRows();i++)
{
if(userList.isIndexSelected(i))
{
if(!userList.getSelectedItem().toString().equals(userName))
{
who=userName.trim()+"对"+userList.getSelectedItem()+"悄悄地说";
}
else
{
JOptionPane.showMessageDialog(null, "你不能给自己发信息,请您重新选择");
jtaSend.setText("");
}
}
}
}
String temp = who + jtaSend.getText().trim();
if (temp!=null&& !temp.equals(""))
{
try
{
dataOut.writeUTF(temp);
jtaSend.setText("");
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
//outMessage.flush();
}
}
}
public static String getDate()
{
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance();// 系统默认日期时间
String time = dateFormat.format(date);
return time;
}
}