问题描述
已经功能达到:一个用户登录用户yxc登录,就可以发送信息第二个用户登录,用户(yxc2)登录,就可以发送信息。再打开一个页面,还是这个登录的用户(yxc2)发送信息。在发送信息也是这个用户(yxc2)问题:能否开两个页面,在本机做到交互,两个用户,请问思路提示,还有代码,是否需要网络编程基础,这个没见过,高手指点一下小弟!
解决方案
解决方案二:
呵呵,我的做法是存在公共区域,比如:context。我当时使用scock做的。不过有个缺点。。。只能一个对一个说话~!
解决方案三:
不断的读取数据库
解决方案四:
packagechattingRoom;importjava.awt.BorderLayout;importjava.awt.FlowLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.ArrayList;importjava.util.List;importjavax.swing.BoxLayout;importjavax.swing.JButton;importjavax.swing.JComboBox;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;importjavax.swing.JTextField;publicclassChatRoomClient{privateJFrameframe;privateJTextAreaarea;privateJLabellabel;privateJComboBoxbox;privateJTextFieldfield;privateJButtonbutton;privateJPaneleastPanel;privateSockets;privatePrintWriterpw;privateBufferedReaderbr;privateList<String>onlineUserList;privateStringuserName;publicChatRoomClient(){createSocket();login();onlineUserList=newArrayList<String>();frame=newJFrame("网络聊天室客户端");area=newJTextArea(20,40);label=newJLabel(userName);box=newJComboBox();field=newJTextField(25);button=newJButton("发送");init();addEventHandler();}privatevoidcreateSocket(){try{s=newSocket("127.0.0.1",9090);pw=newPrintWriter(s.getOutputStream());br=newBufferedReader(newInputStreamReader(s.getInputStream()));}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}privatevoidlogin(){do{Stringstr=JOptionPane.showInputDialog(frame,"请输入昵称:");pw.println("%LOGIN%:"+str);pw.flush();Stringresponse=null;try{response=br.readLine();}catch(IOExceptione){e.printStackTrace();}if(response!=null&&response.split(":")[0].equals("%LOGIN%")&&response.split(":")[1].equals("OK")){userName=str;break;}else{JOptionPane.showMessageDialog(frame,"已经存在同名昵称,请重新输入!");}}while(true);}privatevoidinit(){frame.setLayout(newBorderLayout());JScrollPanejsp=newJScrollPane(area);frame.add(jsp,BorderLayout.CENTER);JPanelsouthPanel=newJPanel();southPanel.setLayout(newFlowLayout());southPanel.add(label);southPanel.add(newJLabel("对"));southPanel.add(box);southPanel.add(newJLabel("说:"));southPanel.add(field);southPanel.add(button);frame.add(southPanel,BorderLayout.SOUTH);eastPanel=newJPanel();eastPanel.setLayout(newBoxLayout(eastPanel,BoxLayout.Y_AXIS));eastPanel.add(newJLabel("在线用户列表:"));frame.add(eastPanel,BorderLayout.EAST);}privatevoidaddEventHandler(){ActionListenerlis=newActionListener(){publicvoidactionPerformed(ActionEvente){if(field.getText().trim().equals("")){JOptionPane.showMessageDialog(frame,"不能发送空消息!");return;}Stringstr="%MESSAGE%:"+userName+":"+box.getSelectedItem()+":"+field.getText();pw.println(str);pw.flush();field.setText("");}};button.addActionListener(lis);field.addActionListener(lis);frame.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){intop=JOptionPane.showConfirmDialog(frame,"确定要离开聊天室吗?","确认退出",JOptionPane.YES_NO_OPTION);if(op==JOptionPane.YES_OPTION){pw.println("%EXIT%:"+userName);pw.flush();try{Thread.sleep(300);s.close();}catch(InterruptedExceptione1){e1.printStackTrace();}catch(IOExceptione1){e1.printStackTrace();}System.exit(0);}}});}privatevoidreflushUserList(){box.removeAllItems();box.addItem("所有人");eastPanel.removeAll();eastPanel.add(newJLabel("在线用户列表:"));eastPanel.add(newJButton("所有人"));JButtonbut;for(Stringuser:onlineUserList){box.addItem(user);eastPanel.add(but=newJButton(user));but.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){Stringstr=e.getActionCommand();box.setSelectedItem(str);}});}}publicvoidshowMe(){frame.pack();frame.setVisible(true);frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);newReadMessageThread().start();}classReadMessageThreadextendsThread{publicvoidrun(){while(true){Stringcomm=null;try{comm=br.readLine();}catch(IOExceptione){e.printStackTrace();}if(comm==null){continue;}if(comm.split(":")[0].equals("%MESSAGE%")){Stringfrom=comm.split(":")[1];Stringto=comm.split(":")[2];Stringcontent=comm.split(":")[3];if(from.equals("SYSTEM")){area.append("[系统消息]:"+content+"n");}else{area.append(from+"对"+to+"说:"+content+"n");}}elseif(comm.split(":")[0].equals("%USERLIST%")){String[]userArray=comm.split(":")[1].split(";");onlineUserList.clear();for(Stringuser:userArray){onlineUserList.add(user);}reflushUserList();}}}}publicstaticvoidmain(String[]args){newChatRoomClient().showMe();}}
packagechattingRoom;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Collection;importjava.util.Date;importjava.util.Hashtable;importjava.util.Map;importjava.util.Set;publicclassChatRoomServer{privateServerSocketss;privateMap<String,Socket>onlineUsers;publicChatRoomServer(){try{ss=newServerSocket(9090);onlineUsers=newHashtable<String,Socket>();}catch(IOExceptione){e.printStackTrace();}}publicvoidstartService(){Sockets=null;try{while(true){s=ss.accept();newChatRoomServerThread(s).start();}}catch(IOExceptione){e.printStackTrace();}}classChatRoomServerThreadextendsThread{privateSockets;privateBufferedReaderbr;privatePrintWriterpw;publicChatRoomServerThread(Sockets){this.s=s;try{br=newBufferedReader(newInputStreamReader(s.getInputStream()));pw=newPrintWriter(s.getOutputStream());}catch(IOExceptione){e.printStackTrace();}}publicvoidrun(){while(true){Stringcomm=null;try{comm=br.readLine();}catch(IOExceptione1){e1.printStackTrace();}if(comm.split(":")[0].equals("%LOGIN%")){StringuserName=comm.split(":")[1];if(onlineUsers.containsKey(userName)){pw.println("%LOGIN%:REFUSE");pw.flush();}else{pw.println("%LOGIN%:OK");pw.flush();onlineUsers.put(userName,s);sendMessageToAllClient("%MESSAGE%:SYSTEM:所有人:"+userName+"进入聊天室!");sendOnlineUserList();}}elseif(comm.split(":")[0].equals("%MESSAGE%")){Stringto=comm.split(":")[2];if(to.equals("所有人")){sendMessageToAllClient(comm);}else{sendMessageToClient(comm,to);}}elseif(comm.split(":")[0].equals("%EXIT%")){Stringuser=comm.split(":")[1];onlineUsers.remove(user);sendMessageToAllClient("%MESSAGE%:SYSTEM:所有人:"+user+"离开聊天室!");sendOnlineUserList();try{s.close();}catch(IOExceptione){e.printStackTrace();}break;}}}//runend!privatevoidsendOnlineUserList(){Set<String>userSet=onlineUsers.keySet();Object[]userArray=userSet.toArray();StringBufferuserListString=newStringBuffer();for(inti=0;i<userArray.length;i++){userListString.append(userArray[i]);if(i<userArray.length-1){userListString.append(";");}}sendMessageToAllClient("%USERLIST%:"+userListString);}privatevoidsendMessageToClient(Stringmesg,StringclientUserName){Sockettemp_s=onlineUsers.get(clientUserName);PrintWriterpw=null;try{pw=newPrintWriter(temp_s.getOutputStream());pw.println(mesg+"t["+newDate()+"]");pw.flush();}catch(IOExceptione){e.printStackTrace();}}privatevoidsendMessageToAllClient(Stringmesg){Collection<Socket>coll=onlineUsers.values();Datedate=newDate();for(Sockettemp_s:coll){PrintWriterpw=null;try{pw=newPrintWriter(temp_s.getOutputStream());}catch(IOExceptione){e.printStackTrace();}if(mesg.split(":")[0].equals("%MESSAGE%")){pw.println(mesg+"t["+date+"]");pw.flush();}else{pw.println(mesg);pw.flush();}}}}/***@paramargs*/publicstaticvoidmain(String[]args){newChatRoomServer().startService();}}
解决方案五:
packagechattingRoom;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.Socket;importjava.net.UnknownHostException;publicclassTCPClientA{privateSockets;publicTCPClientA(){try{s=newSocket("127.0.0.1",8090);}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}publicvoidgo(){BufferedReaderbr=null;try{br=newBufferedReader(newInputStreamReader(s.getInputStream()));Stringstr=br.readLine();System.out.println("当前服务器系统时间:"+str);}catch(IOExceptione){e.printStackTrace();}}/***@paramargs*/publicstaticvoidmain(String[]args){newTCPClientA().go();}}
packagechattingRoom;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.Scanner;publicclassTCPClientB{privateSockets;publicTCPClientB(){try{s=newSocket("127.0.0.1",8091);}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}publicvoidgo(){Scannersca=newScanner(System.in);System.out.println("pleaseinputyourwords:");Stringstr=sca.nextLine();PrintWriterpw=null;BufferedReaderbr=null;try{pw=newPrintWriter(s.getOutputStream());pw.println(str);pw.flush();br=newBufferedReader(newInputStreamReader(s.getInputStream()));str=br.readLine();System.out.println(str);}catch(IOExceptione){e.printStackTrace();}}/***@paramargs*/publicstaticvoidmain(String[]args){newTCPClientB().go();}}
解决方案六:
packagechattingRoom;importjava.io.IOException;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Date;publicclassTCPServerA{privateServerSocketss;publicTCPServerA(){try{ss=newServerSocket(8090);}catch(IOExceptione){e.printStackTrace();}}publicvoidstartService(){Sockets=null;PrintWriterpw=null;try{s=ss.accept();pw=newPrintWriter(s.getOutputStream());pw.println(newDate());pw.flush();}catch(IOExceptione){e.printStackTrace();}finally{if(s!=null)try{s.close();}catch(IOExceptione){}}}/***@paramargs*/publicstaticvoidmain(String[]args){newTCPServerA().startService();}}
packagechattingRoom;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;publicclassTCPServerB{privateServerSocketss;publicTCPServerB(){try{ss=newServerSocket(8091);}catch(IOExceptione){e.printStackTrace();}}publicvoidstartService(){Sockets=null;try{while(true){s=ss.accept();newServerThread(s).start();}}catch(IOExceptione){e.printStackTrace();}}classServerThreadextendsThread{privateSockets;publicServerThread(Sockets){this.s=s;}publicvoidrun(){BufferedReaderbr=null;PrintWriterpw=null;try{br=newBufferedReader(newInputStreamReader(s.getInputStream()));Stringstr=br.readLine();System.out.println(s.getInetAddress()+":"+str+":"+s.getRemoteSocketAddress());str=str.toUpperCase();try{Thread.sleep(20000);}catch(InterruptedExceptione){e.printStackTrace();}pw=newPrintWriter(s.getOutputStream());pw.println(str);pw.flush();}catch(IOExceptione){e.printStackTrace();}}}/***@paramargs*/publicstaticvoidmain(String[]args){newTCPServerB().startService();}}
解决方案七:
该回复于2011-04-26 08:45:46被版主删除
解决方案八:
http://download.csdn.net/source/3003015