Socket 聊天工具

  1 package cn.davy.mychat;
  2 
  3 import org.eclipse.swt.widgets.Display;
  4 import org.eclipse.swt.widgets.FontDialog;
  5 import org.eclipse.swt.widgets.Shell;
  6 import org.eclipse.swt.layout.FormLayout;
  7 import org.eclipse.swt.widgets.Group;
  8 
  9 import java.io.BufferedInputStream;
 10 import java.io.BufferedReader;
 11 import java.io.DataOutputStream;
 12 import java.io.IOException;
 13 import java.io.InputStream;
 14 import java.io.InputStreamReader;
 15 import java.net.DatagramPacket;
 16 import java.net.DatagramSocket;
 17 import java.net.InetAddress;
 18 import java.net.ServerSocket;
 19 import java.net.Socket;
 20 import java.net.UnknownHostException;
 21 
 22 import org.eclipse.swt.SWT;
 23 import org.eclipse.swt.layout.FormData;
 24 import org.eclipse.swt.layout.FormAttachment;
 25 import org.eclipse.swt.widgets.Label;
 26 import org.eclipse.swt.widgets.Text;
 27 import org.eclipse.swt.widgets.Button;
 28 import org.eclipse.swt.widgets.ColorDialog;
 29 import org.eclipse.swt.events.SelectionAdapter;
 30 import org.eclipse.swt.events.SelectionEvent;
 31 import org.eclipse.swt.graphics.Color;
 32 import org.eclipse.swt.graphics.Font;
 33 import org.eclipse.swt.graphics.FontData;
 34 import org.eclipse.swt.graphics.RGB;
 35 
 36 public class MyChat {
 37     private Text txtServerIP;
 38     private Text txtPort;
 39     private Text txtReceivedMessage;
 40     private Text txtSendingMsg;
 41 
 42     private int myPort;
 43     private InetAddress myServerAddress;
 44 
 45     private Socket clientSocket = null;
 46     private Socket connectionSocket = null;
 47     private ServerSocket welcomeSocket = null;
 48 
 49     private boolean isClient = true;
 50 
 51     private BufferedReader inFromClient = null;
 52     private DataOutputStream outToClient = null;
 53 
 54     private BufferedReader inFromServer = null;
 55     private DataOutputStream outToServer = null;
 56 
 57     private Button btnConnecting;
 58     private Button btnClose;
 59     private Button btnListening;
 60     private Button btnPing;
 61     private Button btnFontSetting;
 62     private Button btnInputColor;
 63     private Button btnSendingColor;
 64 
 65     /**
 66      * Launch the application.
 67      * 
 68      * @param args
 69      */
 70     public static void main(String[] args) {
 71         try {
 72             MyChat window = new MyChat();
 73             window.open();
 74         } catch (Exception e) {
 75             e.printStackTrace();
 76         }
 77     }
 78 
 79     /**
 80      * Open the window.
 81      */
 82     public void open() {
 83         Display display = Display.getDefault();
 84         Shell shell = new Shell();
 85         shell.setSize(943, 620);
 86         shell.setText("SWT Application");
 87         shell.setLayout(new FormLayout());
 88 
 89         Group group = new Group(shell, SWT.NONE);
 90         group.setText("u4FA6u542Cu529Fu80FD");
 91         group.setLayout(new FormLayout());
 92         FormData fd_group = new FormData();
 93         fd_group.top = new FormAttachment(0, 10);
 94         fd_group.left = new FormAttachment(0, 10);
 95         fd_group.bottom = new FormAttachment(0, 145);
 96         fd_group.right = new FormAttachment(100, -10);
 97         group.setLayoutData(fd_group);
 98 
 99         Label lblNewLabel = new Label(group, SWT.NONE);
100         FormData fd_lblNewLabel = new FormData();
101         fd_lblNewLabel.top = new FormAttachment(0, 10);
102         fd_lblNewLabel.left = new FormAttachment(0, 10);
103         lblNewLabel.setLayoutData(fd_lblNewLabel);
104         lblNewLabel.setText("u5BF9u65B9IPu5730u5740");
105 
106         Label lblPort = new Label(group, SWT.NONE);
107         FormData fd_lblPort = new FormData();
108         fd_lblPort.top = new FormAttachment(lblNewLabel, 21);
109         fd_lblPort.left = new FormAttachment(lblNewLabel, 0, SWT.LEFT);
110         lblPort.setLayoutData(fd_lblPort);
111         lblPort.setText("u7AEFu53E3");
112 
113         txtServerIP = new Text(group, SWT.BORDER);
114         txtServerIP.setText("127.0.0.1");
115         FormData fd_txtServerIP = new FormData();
116         fd_txtServerIP.bottom = new FormAttachment(lblNewLabel, 0, SWT.BOTTOM);
117         fd_txtServerIP.left = new FormAttachment(lblNewLabel, 26);
118         txtServerIP.setLayoutData(fd_txtServerIP);
119 
120         txtPort = new Text(group, SWT.BORDER);
121         txtPort.setText("2016");
122         fd_txtServerIP.right = new FormAttachment(txtPort, 0, SWT.RIGHT);
123         FormData fd_txtPort = new FormData();
124         fd_txtPort.right = new FormAttachment(100, -139);
125         fd_txtPort.left = new FormAttachment(lblPort, 61);
126         fd_txtPort.top = new FormAttachment(lblPort, 0, SWT.TOP);
127         txtPort.setLayoutData(fd_txtPort);
128 
129         Group group_1 = new Group(shell, SWT.NONE);
130         group_1.setText("u6536u53D1u6570u636E");
131         group_1.setLayout(new FormLayout());
132         FormData fd_group_1 = new FormData();
133         fd_group_1.top = new FormAttachment(group, 33);
134         fd_group_1.bottom = new FormAttachment(100, -10);
135         fd_group_1.left = new FormAttachment(0, 10);
136         fd_group_1.right = new FormAttachment(100, -10);
137 
138         btnListening = new Button(group, SWT.NONE);
139         FormData fd_btnListening = new FormData();
140         fd_btnListening.right = new FormAttachment(txtServerIP, 117, SWT.RIGHT);
141         fd_btnListening.top = new FormAttachment(lblNewLabel, -5, SWT.TOP);
142         fd_btnListening.left = new FormAttachment(txtServerIP, 44);
143         btnListening.setLayoutData(fd_btnListening);
144 
145         // 功能一:(服务器端功能)侦听+循环接收
146         /*
147          * (1) 创建线程,处理服务器端的侦听与循环接收功能; (2) 读取port,创建服务器端socket (3) 启动侦听 (4)
148          * 循环接收数据,并显示在控件中
149          */
150         btnListening.addSelectionListener(new SelectionAdapter() {
151             @Override
152             public void widgetSelected(SelectionEvent e) {
153                 btnConnecting.setEnabled(false); // 如果启动侦听功能,则不再使用连接功能
154                 isClient = false; // 服务器端功能
155                 myPort = Integer.parseInt(txtPort.getText().trim());
156 
157                 // 启动程序后,自动进入侦听与循环接收阶段
158                 new Thread() {
159                     public void run() {
160                         try {
161                             welcomeSocket = new ServerSocket(myPort);
162                             connectionSocket = welcomeSocket.accept();
163 
164                             // 用于接收数据
165                             inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
166 
167                             // 用于发送数据
168                             outToClient = new DataOutputStream(connectionSocket.getOutputStream());
169 
170                         } catch (Exception e) {
171                             System.out.println("Error: " + e.toString());
172                         }
173                         // 循环接收数据
174                         while (true) {
175                             try {
176                                 final String messagea = inFromClient.readLine();
177                                 display.asyncExec(new Runnable() {
178                                     @Override
179                                     public void run() {
180                                         txtReceivedMessage.append("对方: " + messagea + "
");
181                                     }
182                                 });
183 
184                             } catch (Exception e) {
185                                 // TODO: handle exception
186                             }
187                         }
188 
189                     }
190                 }.start();
191 
192             }
193         });
194         btnListening.setText("u4FA6u542C");
195 
196         btnConnecting = new Button(group, SWT.NONE);
197 
198         // 功能二:(客户端功能)连接+循环接收
199         /*
200          * (1)
201          */
202         btnConnecting.addSelectionListener(new SelectionAdapter() {
203             @Override
204             public void widgetSelected(SelectionEvent e) {
205                 // 连接服务器,并进入循环接收状态
206                 btnListening.setEnabled(false);
207                 isClient = true; // 客户端功能
208 
209                 try {
210                     myPort = Integer.parseInt(txtPort.getText().trim());
211                     String strServerIP = txtServerIP.getText().trim();
212                     String regex = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
213                     if (strServerIP.matches(regex)) {
214                         myServerAddress = InetAddress.getByName(strServerIP);
215 
216                         clientSocket = new Socket(myServerAddress, myPort); // 创建socket用于连接
217 
218                         outToServer = new DataOutputStream(clientSocket.getOutputStream());
219                         inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
220 
221                     }
222 
223                 } catch (Exception e1) {
224                     e1.printStackTrace();
225                 }
226 
227                 new Thread() {
228                     public void run() {
229                         try {
230                             while (true) {
231 
232                                 final String message1 = inFromServer.readLine();
233                                 display.asyncExec(new Runnable() {
234                                     @Override
235                                     public void run() {
236                                         // TODO Auto-generated method stub
237                                         txtReceivedMessage.append("对方: " + message1 + "
");
238 
239                                     }
240                                 });
241                             }
242                         } catch (Exception e2) {
243                             // TODO: handle exception
244                         }
245                     }
246                 }.start();
247 
248             }
249         });
250         FormData fd_btnConnecting = new FormData();
251         fd_btnConnecting.top = new FormAttachment(lblPort, -5, SWT.TOP);
252         fd_btnConnecting.right = new FormAttachment(btnListening, -3, SWT.RIGHT);
253         fd_btnConnecting.left = new FormAttachment(btnListening, 0, SWT.LEFT);
254         btnConnecting.setLayoutData(fd_btnConnecting);
255         btnConnecting.setText("u8FDEu63A5");
256 
257         btnClose = new Button(group, SWT.NONE);
258 
259         // 功能八:断开连接
260         btnClose.addSelectionListener(new SelectionAdapter() {
261             @Override
262             public void widgetSelected(SelectionEvent e) {
263                 btnListening.setEnabled(true);
264                 btnConnecting.setEnabled(true);
265 
266                 try {
267                     if (clientSocket != null)
268                         clientSocket.close();
269                     if (welcomeSocket != null)
270                         welcomeSocket.close();
271                     if (connectionSocket != null)
272                         connectionSocket.close();
273 
274                 } catch (Exception e2) {
275                     // TODO: handle exception
276                 }
277 
278             }
279         });
280         FormData fd_btnClose = new FormData();
281         fd_btnClose.right = new FormAttachment(btnListening, 0, SWT.RIGHT);
282         fd_btnClose.bottom = new FormAttachment(100, -9);
283         fd_btnClose.left = new FormAttachment(btnListening, 3, SWT.LEFT);
284         btnClose.setLayoutData(fd_btnClose);
285         btnClose.setText("u65ADu5F00u8FDEu63A5");
286         group_1.setLayoutData(fd_group_1);
287 
288         txtReceivedMessage = new Text(group_1, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
289         FormData fd_txtReceivedMessage = new FormData();
290         fd_txtReceivedMessage.bottom = new FormAttachment(100, -183);
291         fd_txtReceivedMessage.top = new FormAttachment(0, 27);
292         fd_txtReceivedMessage.left = new FormAttachment(0, 13);
293         fd_txtReceivedMessage.right = new FormAttachment(100, -16);
294         txtReceivedMessage.setLayoutData(fd_txtReceivedMessage);
295 
296         txtSendingMsg = new Text(group_1, SWT.BORDER);
297         FormData fd_txtSendingMsg = new FormData();
298         fd_txtSendingMsg.top = new FormAttachment(txtReceivedMessage, 23);
299         fd_txtSendingMsg.right = new FormAttachment(txtReceivedMessage, -3, SWT.RIGHT);
300         fd_txtSendingMsg.left = new FormAttachment(txtReceivedMessage, 0, SWT.LEFT);
301         fd_txtSendingMsg.bottom = new FormAttachment(100, -79);
302         txtSendingMsg.setLayoutData(fd_txtSendingMsg);
303 
304         Button btnSend = new Button(group_1, SWT.NONE);
305         // 功能三: 发送数据
306         btnSend.addSelectionListener(new SelectionAdapter() {
307             @Override
308             public void widgetSelected(SelectionEvent e) {
309                 try {
310                     String sendingMessage = txtSendingMsg.getText() + "
";
311                     if (isClient) {
312                         outToServer.writeBytes(sendingMessage);
313                         txtReceivedMessage.append("我: " + sendingMessage);
314                     } else {
315                         outToClient.writeBytes(sendingMessage);
316                         txtReceivedMessage.append("我: " + sendingMessage);
317                     }
318                     txtSendingMsg.setText("");
319 
320                 } catch (Exception e2) {
321                     // TODO: handle exception
322                 }
323 
324             }
325         });
326         FormData fd_btnSend = new FormData();
327         fd_btnSend.top = new FormAttachment(txtSendingMsg, 24);
328         fd_btnSend.right = new FormAttachment(txtReceivedMessage, 0, SWT.RIGHT);
329         btnSend.setLayoutData(fd_btnSend);
330         btnSend.setText("u53D1u9001");
331 
332         btnPing = new Button(group_1, SWT.NONE);
333 
334         // 功能四:ping
335         btnPing.addSelectionListener(new SelectionAdapter() {
336             @Override
337             public void widgetSelected(SelectionEvent e) {
338 
339                 String serverIP = txtServerIP.getText().trim();
340 
341                 try {
342                     Runtime ce = Runtime.getRuntime();
343                     InputStream in = (InputStream) ce.exec("ping " + serverIP).getInputStream();
344                     BufferedInputStream bin = new BufferedInputStream(in);
345                     byte pingInfo[] = new byte[100];
346                     int n;
347                     while ((n = bin.read(pingInfo, 0, 100)) != -1) {
348                         String s = null;
349                         s = new String(pingInfo, 0, n);
350                         txtReceivedMessage.append(s);
351                     }
352                     txtReceivedMessage.append("Over!

");
353                 } catch (Exception ee) {
354                     System.out.println(ee);
355                 }
356 
357             }
358         });
359 
360         FormData fd_btnPing = new FormData();
361         fd_btnPing.bottom = new FormAttachment(btnSend, 0, SWT.BOTTOM);
362         fd_btnPing.left = new FormAttachment(0, 95);
363         btnPing.setLayoutData(fd_btnPing);
364         btnPing.setText("Ping");
365 
366         btnFontSetting = new Button(group_1, SWT.NONE);
367 
368         // 功能五:字体设置
369         btnFontSetting.addSelectionListener(new SelectionAdapter() {
370             @Override
371             public void widgetSelected(SelectionEvent e) {
372                 FontDialog fd = new FontDialog(shell, SWT.NONE);
373                 fd.setText("字体设置");
374                 FontData d = fd.open();
375                 if (d != null) {
376                     txtReceivedMessage.setFont(new Font(display, d));
377                     txtSendingMsg.setFont(new Font(display, d));
378                 }
379             }
380         });
381 
382         FormData fd_btnFontSetting = new FormData();
383         fd_btnFontSetting.top = new FormAttachment(btnSend, 0, SWT.TOP);
384         fd_btnFontSetting.left = new FormAttachment(btnPing, 6);
385         btnFontSetting.setLayoutData(fd_btnFontSetting);
386         btnFontSetting.setText("u5B57u4F53u8BBEu7F6E");
387 
388         btnInputColor = new Button(group_1, SWT.NONE);
389 
390         // 功能六:接收颜色设置
391         btnInputColor.addSelectionListener(new SelectionAdapter() {
392             @Override
393             public void widgetSelected(SelectionEvent e) {
394                 ColorDialog cd = new ColorDialog(shell, SWT.NONE);
395                 cd.setText("接收颜色设置");
396                 RGB rgb = cd.open();
397                 if (rgb != null) {
398                     txtReceivedMessage.setBackground(new Color(display, rgb.red, rgb.green, rgb.blue));
399                 }
400             }
401         });
402         FormData fd_btnInputColor = new FormData();
403         fd_btnInputColor.bottom = new FormAttachment(btnSend, 0, SWT.BOTTOM);
404         fd_btnInputColor.left = new FormAttachment(btnFontSetting, 6);
405         btnInputColor.setLayoutData(fd_btnInputColor);
406         btnInputColor.setText("u63A5u6536u989Cu8272");
407 
408         btnSendingColor = new Button(group_1, SWT.NONE);
409 
410         // 功能七:发送颜色设置
411         btnSendingColor.addSelectionListener(new SelectionAdapter() {
412             @Override
413             public void widgetSelected(SelectionEvent e) {
414                 ColorDialog cd = new ColorDialog(shell, SWT.NONE);
415                 cd.setText("发送颜色设置");
416                 RGB rgb = cd.open();
417                 if (rgb != null) {
418                     txtSendingMsg.setBackground(new Color(display, rgb.red, rgb.green, rgb.blue));
419                 }
420             }
421         });
422         btnSendingColor.setText("u53D1u9001u989Cu8272");
423         FormData fd_btnSendingColor = new FormData();
424         fd_btnSendingColor.top = new FormAttachment(btnSend, 0, SWT.TOP);
425         fd_btnSendingColor.left = new FormAttachment(btnInputColor, 6);
426         btnSendingColor.setLayoutData(fd_btnSendingColor);
427 
428         shell.open();
429         shell.layout();
430 
431         while (!shell.isDisposed()) {
432             if (!display.readAndDispatch()) {
433                 display.sleep();
434             }
435         }
436     }
437 }
原文地址:https://www.cnblogs.com/0Nullptr/p/6740422.html