我写了个聊天室的程序 感觉正确就是登录完毕后 聊天窗口不能互相聊天
请各位好朋友帮帮忙看下 我怎么也检查不出错误!!
目前登录没问题
就是登录完后不能正常运行,不能互相聊天
请知道的朋友帮忙看下代码
登录窗口和数据库如下
Server.java
import java.awt.List;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
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;
}
}
请各位好朋友帮帮忙看下 我怎么也检查不出错误!!
目前登录没问题
就是登录完后不能正常运行,不能互相聊天
请知道的朋友帮忙看下代码
登录窗口和数据库如下
Server.java
import java.awt.List;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
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;
}
}
解决方案 »
- 求教一个窗口最大化有点灵异的问题
- 用mina2做的消息系统服务,程序重新启动端口被占用问题, 标题要长 .................
- Eclipse 编译 JFrame的子类不过,DOS下是好的。
- 请教个问题.
- 程序调试时出现“ class file editor source not found”,请教各位问是怎么回事?
- 对于变量的初始化
- JBulder做数据库程序的好书在哪里?JBuilder 怎样做数据库的报表显示和打印?
- start 和 join
- 紧急求救(关于Jtable),一经解决马上加分!
- 百分求教!简单问题
- 把BufferedReader里存的email对比 请大家帮忙
- japplet问题请教
楼主【yongchao940】截止到2008-06-25 12:02:29的历史汇总数据(不包括此帖):
发帖数:3 发帖分:60
结贴数:1 结贴分:20
未结数:2 未结分:40
结贴率:33.33 % 结分率:33.33 %
楼主该结一些帖子了
package qq;import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
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;
}}
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;public class LogOn extends JFrame implements ActionListener
{
private JTextField jtfUser = null, jtfIP = null;
private JPasswordField jpfpwd = null;
private JButton jbLogin, jbLogon, jbExit;
Socket socket;
String username ;//用户名
String ip;//服务ip
String outMessage;
String inMessage;//接受的消息
private DataOutputStream dataOut;
private DataInputStream dataIn; public LogOn()
{
super("登录");
jtfUser = new JTextField(15);
jtfIP = new JTextField(15);
jpfpwd = new JPasswordField(15);
jbLogin = new JButton("注册");
jbLogin.addActionListener(this);
jbLogon = new JButton("登录");
jbLogon.addActionListener(this);
jbExit = new JButton("退出");
jbExit.addActionListener(this); Box box1 = Box.createVerticalBox();
box1.add(new JLabel("用户名:"));
box1.add(new JLabel("密 码:"));
box1.add(new JLabel("服务器IP:"));
Box box2 = Box.createVerticalBox();
box2.add(jtfUser);
box2.add(jpfpwd);
box2.add(jtfIP);
Box boxbase = Box.createHorizontalBox();
boxbase.add(box1);
boxbase.add(box2); JPanel jpCenter = new JPanel();
jpCenter.add(boxbase); JPanel jpSouth = new JPanel();
jpSouth.add(jbLogon);
jpSouth.add(jbLogin);
jpSouth.add(jbExit); JLabel jl = new JLabel("欢迎来到登录窗口");
Font font = new Font("宋体", Font.BOLD, 20);
jl.setFont(font);
jl.setHorizontalAlignment(JLabel.CENTER);//居中 this.add(jl, BorderLayout.NORTH);
this.add(jpCenter, BorderLayout.CENTER);
this.add(jpSouth, BorderLayout.SOUTH);
this.setVisible(true);
this.setResizable(false);
this.pack();
this.setLocation(350, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.validate(); } public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbExit)
{
System.exit(0);
}
else if (e.getSource() == jbLogon)
{
username = jtfUser.getText().trim();
String password = new String(jpfpwd.getPassword()).trim();
ip = jtfIP.getText().trim();
try
{
socket = new Socket(InetAddress.getByName(ip), 8888);
System.out.println("connect:");
//PrintWriter outMessage = new PrintWriter(socket.getOutputStream());
dataOut=new DataOutputStream(socket.getOutputStream());
dataIn=new DataInputStream(socket.getInputStream());
if (!jtfUser.equals("")&&!password.equals(""))
{
String total = "userinformation#" + username + "#" + password;
dataOut.writeUTF(total);
}
else
{
System.out.println("您没有输入信息");
JOptionPane.showMessageDialog(null, "你没有输入任何信息", "没输入信息",JOptionPane.INFORMATION_MESSAGE);
return;
}
//while(inMessage==null||inMessage.equals(""))
inMessage = dataIn.readUTF();
//inMessage="ok";
if (inMessage.equals("ok"))
{
this.dispose();
new Client(username,socket);
}
else if (inMessage.equals("pwderror"))
{
System.out.println("你所输入的密码不正确");
socket.close();
JOptionPane.showMessageDialog(null, "您输入的密码不正确,请重新确认您的密码!",
"密码错误", JOptionPane.ERROR_MESSAGE);
}
else if (inMessage.equals("nouser"))
{
System.out.println("你所输入的用户不正确");
socket.close();
JOptionPane.showMessageDialog(null,"您输入的用户名不存在,请确认您所输入的用户名", "用户不存在",JOptionPane.ERROR_MESSAGE);
} }
catch (Exception e1)
{
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "登陆失败", "Login...",JOptionPane.ERROR_MESSAGE);
}
}
} public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
new LogOn();
}}
import java.sql.*;
public class DB
{
Connection conn=null;
Statement stmt=null;
ResultSet rst=null;
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=tsxs";
DB()
{
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
}
catch (ClassNotFoundException e)
{
}
try
{
conn=DriverManager.getConnection(url,"sa","lovelyc");
stmt=conn.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public String canLogon(String username, String password)throws SQLException
{
String ssql = "select * from user_info where user_IDN='" + username+ "'";
rst = stmt.executeQuery(ssql);
if (rst.next())
{
String TPassword = rst.getString("user_PWD");
if (TPassword.equals(password))
{
return "ok";
}
else
{
return "pwderror";
}
}
else
{
return "nouser";
}
}
}
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends Chat implements ActionListener
{
private ObjectOutputStream output; //申明私有输出流对象output
private ObjectInputStream input; //申明私有输入流对象input
private ServerSocket server; //申明私有服务器套接字对象server
private Socket connection; //申明私有客户端套接字对象connecetion
private int counter = 1; //定义一个整形变量counter
public Server() //构造公共Server()方法
{super.display(); //引用其父类Chat的display()方法
bFile.addActionListener(this);
bSend.addActionListener(this);
bClose.addActionListener(this);
bCancel.addActionListener(this);
bReceive.addActionListener(this);
bNoReceive.addActionListener(this);
} //临控各按钮
public void runServer() //服务器运行方法runServer()
{ try { // 例外处理
server = new ServerSocket( 5000, 100 );
while ( true )
{
waitForConnection();
getStreams();
processConnection();
closeConnection();
++counter;
}
}
catch ( EOFException eofException )
{
System.out.println( "对方已经终止与你的连接\n" );
}
catch ( IOException ioException )
{
ioException.printStackTrace();
}
}
private void waitForConnection() throws IOException
{ ta1.setText( "很抱歉,对方不再线!\n请等待对方上线\n" );
connection = server.accept();
ta1.append( "Connection " + counter+" received from: " +
connection.getInetAddress().getHostName() );
}
private void getStreams() throws IOException
{ output = new ObjectOutputStream(
connection.getOutputStream() );
output.flush();
input = new ObjectInputStream(
connection.getInputStream() );
ta1.append( "\n得到 I/O 流\n" );
}
private void processConnection() throws IOException
{String message = "我们之间已经建立了连接!\n我们之间可以聊天和发送传输文件啦!";
output.writeObject( message );
output.flush();
ta2.setEnabled( true );
do{try {
message = ( String ) input.readObject();
ta1.append("\n" + message );
ta1.setCaretPosition(
ta1.getText().length() );
}
catch ( ClassNotFoundException classNotFoundException )
{
ta1.append( "\nUnknown object type received" );
}
} while ( !message.equals( "CLIENT>>> TERMINATE" ) );
}
// close streams and socket
private void closeConnection() throws IOException
{
ta1.append( "\n对方暂停连接" );
ta2.setEnabled( false );
output.close();
input.close();
connection.close();
}
private void sendData( String message )
{ try {
output.writeObject( Nic+"说:\n " + message );
output.flush();
ta1.append( "\n" + message );
}
catch ( IOException ioException )
{
ta1.append( "\nError writing object" );
}
}
public void sendFile()
{
fd=new FileDialog(fChat,"OPEN",FileDialog.LOAD);
fd.setVisible(true);
bCancel.setEnabled(true);
//创建文件流用来读取文件中的数据
File file=new File(fd.getDirectory(),fd.getFile());
FileInputStream fis;
try
{
fis=new FileInputStream(file);
ta1.append("\n你正在向对方发送文件"+file.getAbsoluteFile());
ServerSocket ss=new ServerSocket(5001);
Socket client=ss.accept();
//创建网络输出流并提供数据包装器
OutputStream netOut=client.getOutputStream();
OutputStream doc=new DataOutputStream(new BufferedOutputStream(netOut));
sendData(fd.getFile()); //创建文件读取缓冲区
byte[] buf=new byte[5001];
int num=fis.read(buf);
while(num!=(-1))
{ //是否读完文件
doc.write(buf,0,num);//把文件数据写出网络缓冲区
doc.flush();//刷新缓冲区把数据写往客户端
num=fis.read(buf);//继续从文件中读取数据
}
fis.close();
doc.close();
}
catch(FileNotFoundException fe)
{
ta1.append("\n很抱歉,你发送的文件不存在!") ;
} //创建网络服务器接受客户请求
catch(IOException ioe)
{
ta1.append(ioe.getMessage());
}
}
public void receiveFile()
{fd=new FileDialog(fChat,"SAVE",FileDialog.SAVE);
fd.setVisible(true); //使用本地文件系统接受网络数据并存为新文件
File file=new File("feilong");
try
{
file.createNewFile();
RandomAccessFile raf=new RandomAccessFile(file,"rw");
// 通过Socket连接文件服务器
Socket server=new Socket(InetAddress.getLocalHost(),5001);
//创建网络接受流接受服务器文件数据
InputStream netIn=server.getInputStream();
InputStream in=new DataInputStream(new BufferedInputStream(netIn));
//创建缓冲区缓冲网络数据
byte[] buf=new byte[5000];
int num=in.read(buf);
while(num!=(-1))
{ //是否读完所有数据
raf.write(buf,0,num);//将数据写往文件
raf.skipBytes(num);//顺序写文件字节
num=in.read(buf);//继续从网络中读取文件
}
in.close();
raf.close();
}
catch(FileNotFoundException fe)
{
ta1.append("文件不存在!") ;
} //创建网络服务器接受客户请求
catch(IOException ioe)
{
ta1.append(ioe.getMessage());
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bFile)
{
sendFile();
bCancel.setEnabled(true);
}
else
if(e.getSource()==bReceive)
{
receiveFile();
}
else
if(e.getSource()==bSend)
{
String send;
send=ta1.getText()+"\n"+Nic+"说:\n"+ta2.getText();
sendData( ta2.getText() );
ta1.setText(send);
ta2.setText("");
ta2.setFocusable(true);
}
else
if(e.getSource()==bClose)
{
System.exit(0);
}
}
}