java socket/swing聊天系统

上个周五的下午,在公司闲来无事,
写了个小程序玩玩,
稍微测试了一下,居然能用!
但由于代码量较少,也谈不上什么设计,
发上来算是个备忘吧:
服务器端程序:
  1. packagecom.test.talk;
  2. importjava.awt.BorderLayout;
  3. importjava.awt.FlowLayout;
  4. importjava.awt.event.ActionEvent;
  5. importjava.awt.event.ActionListener;
  6. importjava.awt.event.WindowAdapter;
  7. importjava.awt.event.WindowEvent;
  8. importjava.io.DataInputStream;
  9. importjava.io.DataOutputStream;
  10. importjava.io.IOException;
  11. importjava.net.BindException;
  12. importjava.net.ServerSocket;
  13. importjava.net.Socket;
  14. importjava.util.LinkedList;
  15. importjava.util.List;
  16. importjavax.swing.JButton;
  17. importjavax.swing.JFrame;
  18. importjavax.swing.JLabel;
  19. importjavax.swing.JPanel;
  20. importjavax.swing.JTextField;
  21. publicclassServerextendsJFrame
  22. {
  23. booleanstarted=false;
  24. privateServerSocketss=null;
  25. privateListclientList=newLinkedList();
  26. privateJLabelportLbl=null;
  27. privateJTextFieldportTxt=null;
  28. privateJButtonportSetBtn=null;
  29. privateStringport=null;
  30. privateJButtonstartBtn=null;
  31. privateJButtonstopBtn=null;
  32. privateJPanelmainPanle=null;
  33. privateJPanelheadPanle=null;
  34. publicstaticvoidmain(String[]args)
  35. {
  36. newServer();
  37. }
  38. publicServer()
  39. {
  40. headPanle=newJPanel(newFlowLayout(FlowLayout.LEFT));
  41. portLbl=newJLabel("PORT");
  42. portTxt=newJTextField(7);
  43. portSetBtn=newJButton("OK");
  44. portSetBtn.addActionListener(newActionListener()
  45. {
  46. publicvoidactionPerformed(ActionEvente)
  47. {
  48. if(portTxt.getText().matches("//d+"))
  49. {
  50. port=portTxt.getText();
  51. startBtn.setEnabled(true);
  52. stopBtn.setEnabled(true);
  53. }
  54. else
  55. {
  56. javax.swing.JOptionPane.showMessageDialog(null,"portbeinputtedisillegal");
  57. }
  58. }
  59. });
  60. headPanle.add(portLbl);
  61. headPanle.add(portTxt);
  62. headPanle.add(portSetBtn);
  63. getContentPane().add(headPanle,BorderLayout.NORTH);
  64. startBtn=newJButton("Start");
  65. stopBtn=newJButton("Stop");
  66. startBtn.setEnabled(false);
  67. stopBtn.setEnabled(false);
  68. mainPanle=newJPanel(newFlowLayout(FlowLayout.CENTER));
  69. startBtn.addActionListener(newStartClickListener());
  70. stopBtn.addActionListener(newActionListener()
  71. {
  72. publicvoidactionPerformed(ActionEvente)
  73. {
  74. started=false;
  75. clientList.clear();
  76. try
  77. {
  78. if(ss!=null)
  79. {
  80. ss.close();
  81. }
  82. }
  83. catch(IOExceptione1)
  84. {
  85. e1.printStackTrace();
  86. }
  87. }
  88. });
  89. mainPanle.add(startBtn);
  90. mainPanle.add(stopBtn);
  91. getContentPane().add(mainPanle,BorderLayout.CENTER);
  92. addWindowListener(newWindowAdapter()
  93. {
  94. publicvoidwindowClosing(WindowEvente)
  95. {
  96. started=false;
  97. clientList.clear();
  98. try
  99. {
  100. if(ss!=null)
  101. {
  102. ss.close();
  103. }
  104. }
  105. catch(IOExceptione1)
  106. {
  107. e1.printStackTrace();
  108. }
  109. System.exit(0);
  110. }
  111. });
  112. this.setSize(300,300);
  113. setLocation(100,100);
  114. pack();
  115. setVisible(true);
  116. }
  117. privatevoidstart()
  118. {
  119. try
  120. {
  121. ss=newServerSocket(Integer.parseInt(port));
  122. started=true;
  123. }
  124. catch(BindExceptionbe)
  125. {
  126. javax.swing.JOptionPane.showMessageDialog(null,"portisuseingbyothers");
  127. }
  128. catch(IOExceptione)
  129. {
  130. javax.swing.JOptionPane.showMessageDialog(null,"connectserverfail");
  131. }
  132. try
  133. {
  134. while(started)
  135. {
  136. Sockets=ss.accept();
  137. ClientImplcr=newClientImpl(s);
  138. newThread(cr).start();
  139. clientList.add(cr);
  140. System.out.println("SystemInfo:"+s.getInetAddress()+"connectsuccessfully");
  141. }
  142. }
  143. catch(IOExceptione)
  144. {
  145. System.out.println("Clientclosed!");
  146. }
  147. }
  148. classClientImplimplementsRunnable
  149. {
  150. privateSockets;
  151. privateDataInputStreamdis=null;
  152. privateDataOutputStreamdos=null;
  153. booleanbConnect=false;
  154. publicClientImpl(Sockets)
  155. {
  156. this.s=s;
  157. try
  158. {
  159. dis=newDataInputStream(s.getInputStream());
  160. dos=newDataOutputStream(s.getOutputStream());
  161. bConnect=true;
  162. }
  163. catch(IOExceptione)
  164. {
  165. e.printStackTrace();
  166. }
  167. }
  168. privatevoidsend(Stringstr)
  169. {
  170. try
  171. {
  172. dos.writeUTF(str);
  173. }
  174. catch(IOExceptione)
  175. {
  176. e.printStackTrace();
  177. }
  178. }
  179. publicvoidrun()
  180. {
  181. ClientImplcr=null;
  182. try
  183. {
  184. while(bConnect)
  185. {
  186. Stringstr=dis.readUTF();
  187. System.out.println(str);
  188. for(inti=0;i<clientList.size();i++)
  189. {
  190. cr=(ClientImpl)clientList.get(i);
  191. cr.send(str);
  192. }
  193. }
  194. }
  195. catch(Exceptione)
  196. {
  197. clientList.remove(cr);
  198. System.out.println(s.getInetAddress()+"hasleaved");
  199. }
  200. finally
  201. {
  202. try
  203. {
  204. if(dis!=null)
  205. dis.close();
  206. if(dos!=null)
  207. dos.close();
  208. if(s!=null)
  209. {
  210. s.close();
  211. s=null;
  212. }
  213. }
  214. catch(IOExceptionio)
  215. {
  216. io.printStackTrace();
  217. }
  218. }
  219. }
  220. }
  221. classStartClickListenerimplementsRunnable,ActionListener
  222. {
  223. publicvoidactionPerformed(ActionEvente)
  224. {
  225. newThread(this).start();
  226. }
  227. publicvoidrun()
  228. {
  229. start();
  230. }
  231. }
  232. }
客户端程序:
  1. packagecom.test.talk;
  2. importjava.awt.BorderLayout;
  3. importjava.awt.FlowLayout;
  4. importjava.awt.event.ActionEvent;
  5. importjava.awt.event.ActionListener;
  6. importjava.awt.event.WindowAdapter;
  7. importjava.awt.event.WindowEvent;
  8. importjava.io.DataInputStream;
  9. importjava.io.DataOutputStream;
  10. importjava.io.IOException;
  11. importjava.net.Socket;
  12. importjava.net.UnknownHostException;
  13. importjavax.swing.JButton;
  14. importjavax.swing.JFrame;
  15. importjavax.swing.JLabel;
  16. importjavax.swing.JPanel;
  17. importjavax.swing.JTextArea;
  18. importjavax.swing.JTextField;
  19. /**
  20. *Client
  21. *
  22. *@authorhx0272
  23. *
  24. */
  25. publicclassClient
  26. {
  27. publicstaticvoidmain(String[]args)
  28. {
  29. ClientFrameframe=newClientFrame();
  30. }
  31. }
  32. classClientFrameextendsJFrame
  33. {
  34. privateJPanelmainPanel;
  35. privateJPanelheadPanel;
  36. privateJPanelfootPanel;
  37. privateJTextAreashowArea;
  38. privateJTextFieldinputTxt;
  39. privateJLabelportLbl;
  40. privateJLabelipLbl;
  41. privateJLabelnameLbl;
  42. privateJTextFieldportTxt;
  43. privateJTextFieldipTxt;
  44. privateJTextFieldnameTxt;
  45. privateJButtonsubmitBtn;
  46. privateJButtonnameBtn;
  47. privateJButtonloginBtn;
  48. privateSocketclientSocket=null;
  49. privateDataOutputStreamdos=null;
  50. privateDataInputStreamdis=null;
  51. privatebooleanbConnect=false;
  52. privateStringname="";
  53. publicClientFrame()
  54. {
  55. init();
  56. }
  57. privatevoidinit()
  58. {
  59. //mainpanelBegin
  60. mainPanel=newJPanel();
  61. showArea=newJTextArea(15,80);
  62. showArea.setEditable(false);
  63. mainPanel.add(showArea);
  64. getContentPane().add(mainPanel,BorderLayout.CENTER);
  65. //mainpanelEnd
  66. //headpanelBegin
  67. headPanel=newJPanel(newFlowLayout(FlowLayout.LEFT));
  68. portLbl=newJLabel("PORT");
  69. portTxt=newJTextField(7);
  70. ipLbl=newJLabel("IP");
  71. ipTxt=newJTextField(25);
  72. nameLbl=newJLabel("name");
  73. nameTxt=newJTextField(15);
  74. nameBtn=newJButton("OK");
  75. loginBtn=newJButton("login");
  76. nameBtn.addActionListener(newActionListener()
  77. {
  78. publicvoidactionPerformed(ActionEvente)
  79. {
  80. Stringtmp=nameTxt.getText();
  81. if(tmp!=null||!tmp.equals(""))
  82. {
  83. intid=javax.swing.JOptionPane.showConfirmDialog(null,"yesorno","chooseyes",
  84. javax.swing.JOptionPane.OK_OPTION);
  85. if(id==0)
  86. {
  87. name=nameTxt.getText();
  88. loginBtn.setEnabled(true);
  89. nameBtn.setEnabled(false);
  90. }
  91. }
  92. }
  93. });
  94. headPanel.add(portLbl);
  95. headPanel.add(portTxt);
  96. headPanel.add(ipLbl);
  97. headPanel.add(ipTxt);
  98. headPanel.add(loginBtn);
  99. headPanel.add(nameLbl);
  100. headPanel.add(nameTxt);
  101. headPanel.add(nameBtn);
  102. loginBtn.setEnabled(false);
  103. loginBtn.addActionListener(newButtonClickAction());
  104. getContentPane().add(headPanel,BorderLayout.NORTH);
  105. //headpanelEnd
  106. //footpanelBegin
  107. footPanel=newJPanel(newFlowLayout(FlowLayout.LEFT));
  108. inputTxt=newJTextField(70);
  109. submitBtn=newJButton("submit");
  110. footPanel.add(inputTxt);
  111. footPanel.add(submitBtn);
  112. submitBtn.addActionListener(newButtonClickAction());
  113. submitBtn.setEnabled(false);
  114. getContentPane().add(footPanel,BorderLayout.SOUTH);
  115. //footpanelEnd
  116. addWindowListener(newWindowAdapter()
  117. {
  118. publicvoidwindowClosing(WindowEvente)
  119. {
  120. disConnect();
  121. System.exit(0);
  122. }
  123. });
  124. this.setSize(300,300);
  125. setLocation(100,100);
  126. pack();
  127. setVisible(true);
  128. }
  129. /**
  130. *loginbutton/submitbuttonactionlistener
  131. *
  132. *@authorhx0272
  133. *
  134. */
  135. classButtonClickActionimplementsActionListener
  136. {
  137. publicvoidactionPerformed(ActionEvente)
  138. {
  139. if("submit".equals(e.getActionCommand()))
  140. {
  141. Stringstr=inputTxt.getText().trim();
  142. inputTxt.setText("");
  143. sendToServer(str);
  144. }
  145. elseif("login".equals(e.getActionCommand()))
  146. {
  147. connect();
  148. }
  149. }
  150. }
  151. /**
  152. *enterbeinputtedevent
  153. *
  154. *@authorhx0272
  155. */
  156. classEnterClickActionimplementsActionListener
  157. {
  158. publicvoidactionPerformed(ActionEvente)
  159. {
  160. Stringstr=inputTxt.getText().trim();
  161. inputTxt.setText("");
  162. sendToServer(str);
  163. }
  164. }
  165. /**
  166. *sendmessagetoserver
  167. *
  168. *@authorhx0272
  169. */
  170. privatevoidsendToServer(Stringstr)
  171. {
  172. try
  173. {
  174. dos.writeUTF(name+":"+str);
  175. dos.flush();
  176. }
  177. catch(IOExceptione)
  178. {
  179. e.printStackTrace();
  180. }
  181. }
  182. /**
  183. *closeresource
  184. *
  185. *@authorhx0272
  186. */
  187. privatevoiddisConnect()
  188. {
  189. try
  190. {
  191. //clientSocket.close();
  192. //
  193. //dos.close();
  194. bConnect=false;
  195. }
  196. catch(Exceptione)
  197. {
  198. e.printStackTrace();
  199. }
  200. }
  201. /**
  202. *receivemessagefromserver
  203. *
  204. *@authorhx0272
  205. */
  206. privateclassReceiveimplementsRunnable
  207. {
  208. publicvoidrun()
  209. {
  210. try
  211. {
  212. while(bConnect)
  213. {
  214. Stringstr=dis.readUTF();
  215. showArea.setText(showArea.getText()+str+'/n');
  216. }
  217. }
  218. catch(IOExceptione)
  219. {
  220. javax.swing.JOptionPane.showMessageDialog(null,"connectservererror");
  221. }
  222. }
  223. }
  224. /**
  225. *connectionbegin
  226. *
  227. *@authorhx0272
  228. */
  229. privatevoidconnect()
  230. {
  231. try
  232. {
  233. if(ipTxt.getText().matches("//d{1,3}.//d{1,3}.//d{1,3}.//d{1,3}")&&portTxt.getText().matches("//d+"))
  234. {
  235. clientSocket=newSocket(ipTxt.getText(),Integer.parseInt(portTxt.getText()));
  236. dos=newDataOutputStream(clientSocket.getOutputStream());
  237. dis=newDataInputStream(clientSocket.getInputStream());
  238. bConnect=true;
  239. newThread(newReceive()).start();
  240. System.out.println("Iamcoming");
  241. javax.swing.JOptionPane.showMessageDialog(null,"connectserversuccess");
  242. submitBtn.setEnabled(true);
  243. inputTxt.addActionListener(newEnterClickAction());
  244. }
  245. else
  246. {
  247. javax.swing.JOptionPane.showMessageDialog(null,"portoripbeinputtedisillegal");
  248. }
  249. }
  250. catch(UnknownHostExceptionuhe)
  251. {
  252. javax.swing.JOptionPane.showMessageDialog(null,"connectservererror");
  253. }
  254. catch(IOExceptione)
  255. {
  256. javax.swing.JOptionPane.showMessageDialog(null,"connectservererror");
  257. }
  258. }
  259. }
使用说明:
1.先运行服务器端程序,设定好端口号
2.点击Start按钮,运行服务器
3.运行客户端程序
4.设定好昵称
5.设定与服务器端匹配的端口号和服务器的ip地址
6.点击Login按钮,登录到聊天系统
7.可以聊天了。

你可能感兴趣的:(java socket)