暑假没事,我想做一个“多人聊天的程序”但是遇到了和JSP一样的问题 链接(服务器端显示用户列表点击与之链接)不能及时更新啊(JSP中可以用ajax) swing 怎么弄啊 求大神指教(利用harsh函数里边的东东)
附上 蛋疼的 代码。
public class myserver {
static Hashtable ht=new Hashtable();
static index a=new index();
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(7891);
Socket s =ss.accept();
InetAddress ips=s.getInetAddress();
String ip=ips.toString().substring(1);
ht.put(ip,s);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class index extends JFrame {
Container con=this.getContentPane();
JLabel jl1=new JLabel("jl1");
FlowLayout gly=new FlowLayout();
JPanel jp=new JPanel(gly);
public index(){
con.add(jp);
this.setSize(200,200);
this.setVisible(true);
}
}
附上 蛋疼的 代码。
public class myserver {
static Hashtable ht=new Hashtable();
static index a=new index();
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(7891);
Socket s =ss.accept();
InetAddress ips=s.getInetAddress();
String ip=ips.toString().substring(1);
ht.put(ip,s);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class index extends JFrame {
Container con=this.getContentPane();
JLabel jl1=new JLabel("jl1");
FlowLayout gly=new FlowLayout();
JPanel jp=new JPanel(gly);
public index(){
con.add(jp);
this.setSize(200,200);
this.setVisible(true);
}
}
第一 用个线程监视着用户是否点击,点击了马上开启另外个刷新UI的线程。个人认为线程多了也不好。
第二 与数据库连接吧,用户点击了马上更新下,不过这样用户访问数据库的次数增加了。最后建议:
采用p2p编程吧,个人感觉还是不错的。
在客户端上线的时候触发。服务器收到客户端的socket连接,然后向已在线的所有客户端广播,某个客户端上线。然后某个客户端下线的时候,断掉socket,再做一次广播。做个demo没问题,但客户端多了,并且上下线频繁会有效率问题。你可以做个好友功能,只广播好友列表里的人,以减轻服务器压力。另外,A客户端想与B客户端私聊,可以在客户端上写一个线程,定期去服务器的私聊请求连接列表里查看有没有向自己申请的连接。过程是这样的:
A向服务器请求与B的私聊,服务器把A的请求放入请求列表里。客户端会定期去检查请求列表,当B发现服务器请求列表里有对自己的请求时,弹出选择框,确认是否同意私聊,并向服务器返回确认请求。服务器将该请求返回给A。如果同意,则A发送给B的信息,经由服务器转发给B。