Java_QQ_源程序代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2010-06-23 20:24:11 TiBack
import .*;
import java.io.*;
import java.sql.*;
import java.util.*;
public class QQServer {
public static void main(String args[]) {
try {
//用户名同步(14)
HashMap
// 服务器在8000端口监听(1)
ServerSocket ss = new ServerSocket(8000);
while (true) {
"服务器正在8000端口监听.....");
Socket s = ss.accept();
MyService t = new MyService();
t.setSocket(s);
t.setHashMap(hm) ;
t.start();
}
} catch (Exception e) {
}
}
}
// 支持多用户登陆(13)
class MyService extends Thread {
private Socket s;
private HashMap
public void setHashMap(HashMap
this.hm = hm ;
}
public void setSocket(Socket s) {
this.s = s;
}
public void run() {
try {
// 接收客户端发送来的用户名和密码(2)
InputStream is = s.getInputStream();
InputStreamRead er isr = new InputStreamRead er(is);
BufferedReader br = new BufferedRead er(isr);
String uandp = br.readLine();
// 拆分(4)
String u = uandp.split("%")[0];
String p = uandp.split("%")[1];
// 到数据库中验证(5)
Class.forName("");
Connection cn = DriverManager.getConnection(
"jdbc:;databasename=wy", "sa",
"123");
PreparedStatement ps = cn
.prepareStatement("select * from username where username=? and password=?"); ps.setString(1, u);
ps.setString(2, p);
ResultSet rs = ps.executeQuery();
// 发送确认信息回客户端(7)
OutputStream os = s.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw, true);
if (rs.next()) {
pw.println("ok");
Thread.sleep(10) ;
//将自己的名字发送给其他人(17)
for(Socket ts : hm.values()){
OutputStream tos = ts.getOutputStream() ;
OutputStreamWriter tosw = new OutputStreamWriter(tos) ;
PrintWriter tpw = new PrintWriter(tosw , true) ;
tpw.println("user%"+u) ;
}
//将其他人的名字发送给自己(18)
for(String tu : hm.keySet()){
pw.println("user%"+tu) ;
}
//将用户名和Socket存入HashMap(15)
hm.put(u, s) ;
// 接收客户端发送来的信息(11)
while (true) {
String message = br.readLine();
//判断是否退出
if(message.equals("{exit}")){
for(Socket ts : hm.values()){
OutputStream tos = ts.getOutputStream() ; OutputStreamWriter tosw = new OutputStreamWriter(tos) ; PrintWriter tpw = new PrintWriter(tosw , true) ;
tpw.println("exit%"+u) ;
}
hm.remove(u) ;
return ;
}
String to = message.split("%")[0] ;
String mess = message.split("%")[1] ;
Socket ts = hm.get(to) ;
OutputStream tos = ts.getOutputStream() ; OutputStreamWriter tosw = new OutputStreamWriter(tos) ; PrintWriter tpw = new PrintWriter(tosw , true) ;
tpw.println("mess%"+mess) ;
}
} else {
pw.println("err");
}
} catch (Exception e) {
}
}
}