8:30-9:00 学习打卡
9:30-12:00 写qq项目
15:00-17:00 写qq项目
1.接收信息map类
将接收到的信息的线程类放到一个map表里,用id来取出线程。
package qqserver.mode;
import java.util.HashMap;
public class Mythreads {
private static HashMap hm=new HashMap<String,Mythread>();
public static void add(String id,Mythread m){//将id和线程放进里面
hm.put(id,m);
}
public static Mythread getthread(String id){//以id找到相应的线程
return (Mythread) hm.get(id);
}
}
2.接收信息的线程
从id中找到的线程并发给线程所做出的回应
package qqserver.mode;
import qqc.massage.Massage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Mythread extends Thread{
Socket s;
public Mythread(Socket s) {
this.s = s;
}
@Override
public void run() {
while(true){
try {
ObjectInputStream ois=new ObjectInputStream(s.getInputStream());
Massage m= (Massage) ois.readObject();
System.out.println(m.getMyid()+"对"+m.getOid()+"说: "+m.getXiaoxi());
// Mythread mt=Mythreads.getthread(m.getOid());
// ObjectOutputStream oos=new ObjectOutputStream(mt.s.getOutputStream());
// oos.writeObject(m);
//目前还有未知错误,还需寻找
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
3.聊天对话框改进,变成了线程的形式,每次进入将会开辟一个线程,负责时刻接收消息。
public class qqchat extends JFrame implements ActionListener,Runnable {
JPanel jp;
JTextField jt;
JTextArea jta;
JButton jb;
private String id;
private String ss;
public qqchat(String id, String ss){
this.id=id;
this.ss=ss;
jt=new JTextField(15);
jta=new JTextArea();
jb=new JButton("发送");
jp=new JPanel();
jp.add(jt);
jp.add(jb);
setTitle(id+"正在和"+ss+"聊天");
add(jta,BorderLayout.CENTER);
add(jp,BorderLayout.SOUTH);
setSize(400,300);
setVisible(true);
}
public static void main(String argv[]){
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb){
Massage m=new Massage();
m.setXiaoxi(jt.getText().trim());
m.setMyid(id);
m.setOid(ss);
try {
ObjectOutputStream oos=new ObjectOutputStream(qqlogin.s.getOutputStream());
oos.writeObject(m);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
@Override//这是当前聊天对话框的线程,时刻接收消息
public void run() {
while(true){
try {
ObjectInputStream ois=new ObjectInputStream(qqlogin.s.getInputStream());
Massage m=(Massage) ois.readObject();
String s=m.getMyid()+" 对 "+m.getOid()+"说: "+m.getXiaoxi()+"\r\t";
jta.append(s);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}