首先开发客户端:
TCP_Client.java:
1 package com.hw.TCP0226;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.net.Socket;
6 import java.net.UnknownHostException;
7 import java.util.Scanner;
8
9 @SuppressWarnings("unused")
10 public class TCP_Client {
11 public static void main(String[] args) throws Exception {
12 Socket s = null;
13 try {
14 s = new Socket("10.0.7.69",7772);
15 Scanner scanner = new Scanner(System.in);
16 s.getOutputStream().write(scanner.nextLine().getBytes());
17 } catch (Exception e) {
18 // TODO Auto-generated catch block
19 e.printStackTrace();
20 } finally {
21 try {
22 if(s != null){
23 s.close();
24 }
25 } catch (IOException e) {
26 // TODO Auto-generated catch block
27 e.printStackTrace();
28 }
29 }
30 }
31 }
然后是服务器端:
TCP_Server.java:
1 package com.hw.TCP0226;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.ServerSocket;
6 import java.net.Socket;
7
8 public class TCP_Server{
9 public static void main(String[] args) {
10 ConnectionThread ct = new ConnectionThread();
11 ct.start();
12 }
13 }
14
15 class ConnectionThread extends Thread{
16 @Override
17 public void run() {
18 ServerSocket ss = null;
19 try {
20 ss = new ServerSocket(7772);
21 while(true)
22 {
23 Socket s = ss.accept();
24 System.out.println("接收到了一个客户端连接:"+s.getInetAddress());
25 new ClientThread(s).start();
26 }
27
28 } catch (IOException e) {
29 // TODO Auto-generated catch block
30 e.printStackTrace();
31 } finally {
32 try {
33 if(ss != null){
34 ss.close();
35 }
36 } catch (IOException e) {
37 // TODO Auto-generated catch block
38 e.printStackTrace();
39 }
40 }
41 }
42 }
43
44 class ClientThread extends Thread {
45
46 private Socket s;
47 public ClientThread(Socket s){
48 this.s = s;
49 }
50
51 @Override
52 public void run() {
53 try {
54 InputStream input = s.getInputStream();
55 byte[] buf = new byte[1024];
56 int length = -1;
57 while((length = input.read(buf)) > -1)
58 {
59 System.out.println(new String(buf,0,length));
60 }
61
62 } catch (IOException e) {
63 // TODO Auto-generated catch block
64 e.printStackTrace();
65 }
66 }
67 }
注意,因为这里我是一个服务器端对应有很多个客户端,所以服务器端在接收数据部分出的代码必须开多线程,建立连接那儿也应该使用循环。其他的就很简单了。
这表示可以对应多个客户端。
OK.
原文:https://www.cnblogs.com/EvanTheGreat/p/14460505.html