今天开始写聊天室项目:
主要思想如图所示
package com.ww.qqserve.service;
import com.ww.qqcommon.MassageType;
import com.ww.qqcommon.Message;
import com.ww.qqcommon.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class QQServer {
private ServerSocket ss=null;
public QQServer(){
System.out.println("服务器在9999端口监听。。。");
try {
ss=new ServerSocket(9999);
while (true){//监听是不断的
Socket socket = ss.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
User u = (User) ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Message message=new Message();
//先验证特殊的,因为这里需要使用到数据库
if(u.getUserId().equals("100")&&u.getPassWd().equals("123456")){//登录成功
message.setMesType(MassageType.MESSAGE_LOGIN_SUCCEED);
oos.writeObject(message);
//创建一个线程,与客户端保持联系。
ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, u.getUserId());
serverConnectClientThread.start();
//把线程对象 放入集合中
}else{//登录失败
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.ww.qqserve.service;
import com.ww.qqcommon.Message;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerConnectClientThread extends Thread {
private Socket socket;
private String userId;//链接到服务器的id
public ServerConnectClientThread(Socket socket, String userId) {
this.socket = socket;
this.userId = userId;
}
@Override
public void run() {
while(true){
System.out.println("服务端与客户端保持通讯,读取数据");
try {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message me = (Message) ois.readObject();
//后面会使用messa
} catch (Exception e) {
e.printStackTrace();
}
}
}
}