山寨QQ
public void creatServer(int port) {// 创建服务器ServerSocket sever;try { sever = new ServerSocket(port); System.out.println("服务器已启动,等待客户端。。。"); while (true) {// 监听获取客户端对象Socket client = sever.accept();new ChatThread(client).start();System.out.println("进入客户端:" + client.getPort()); }} catch (IOException e) {e.printStackTrace();} }
?二.创建一个客户端,并请求链接服务器
public void connetServer() {boolean bool = false;try { Socket client = new Socket("localhost", 4040); // 获取输入输出流对象 InputStream in = client.getInputStream(); br = new BufferedReader(new InputStreamReader(in)); out = client.getOutputStream(); sendMsgToServer(name);// 发送用户名 sendMsgToServer(pwd);// 发送密码} catch (Exception e) {e.printStackTrace();}}
?三.聊天线程的创建
public class ChatThread extends Thread {private Socket client;OutputStream out;InputStream in;String username, password, username2;public void run() {try {chat();} catch (Exception e) {e.printStackTrace();}}// 构造方法public ChatThread(Socket client) {this.client = client;}// 获取线程对应的客户名public String getUsername() {return username;}// 发送信息的方法public void sendMsg(String message) {try {out.write((message + "\r\n").getBytes());} catch (IOException e) {e.printStackTrace();}}// 聊天方法public void chat() throws Exception {// 获取客户端输入输出流in = client.getInputStream();out = client.getOutputStream();BufferedReader br = new BufferedReader(new InputStreamReader(in));username = br.readLine();username2 = br.readLine();System.out.println(username + "-----" + password);ChatTool.addUser(this);String msg = br.readLine(); //当客户端没有说bye并且msg不为空时继续聊while (!"bye".equalsIgnoreCase(msg) && msg != null) {System.out.println(msg);ChatTool.sendMsgToOne(username, username2, msg);msg = br.readLine();}if (msg == null) {ChatTool.moveUser(username);}// 关闭客户端client.close();}}
?四.聊天处理方法
public class ChatTool { public static List<ChatThread> userlist = new ArrayList<ChatThread>();// 添加客户线程对象到队列public static void addUser(ChatThread ct) {userlist.add(ct);}// 从队列移除客户线程对象public static void moveUser(String username) {for (int i = 0; i < userlist.size(); i++) { ChatThread ct = userlist.get(i); if (ct.getUsername().equals(username)) userlist.remove(i); }}// 群发信息public static void sendMsgToAll(String username, String msg) {for (int i = 0; i < userlist.size(); i++) { ChatThread ct = userlist.get(i); ct.sendMsg(username + "说:" + "\r\n" + msg);}}// 单聊public static void sendMsgToOne(String username, String username2,String msg) {for (int i = 0; i < userlist.size(); i++) {ChatThread ct = userlist.get(i);if (ct.getUsername().equals(username2))ct.sendMsg(msg);}}}
?
?