1 package com.socket.tcp;
2
3 import java.io.DataInputStream;
4 import java.io.DataOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.ServerSocket;
9 import java.net.Socket;
10 import java.net.UnknownHostException;
11
12 import org.junit.Test;
13
14 public class TestTCP {
15 @Test
16 public void testTCPServer() {
17 try {
18 ServerSocket ss = new ServerSocket(9999);
19 while (true) {// 需要不断的监听是否有客户端程序连接上来,所以需要不断地监控
20 Socket socket = ss.accept();//阻塞式方法
21 InputStream is = socket.getInputStream();
22 DataInputStream dis = new DataInputStream(is);
23 System.out.println(dis.readUTF());
24 }
25 } catch (IOException e) {
26 e.printStackTrace();
27 }
28 }
29
30 @Test
31 public void testTCPClient() {
32 try {
33 Socket client = new Socket("127.0.0.1", 9999);
34 OutputStream os = client.getOutputStream();
35 DataOutputStream dos = new DataOutputStream(os);
36 dos.writeUTF("Hello Server");
37 dos.flush();
38 dos.close();
39
40 } catch (UnknownHostException e) {
41 e.printStackTrace();
42 } catch (IOException e) {
43 e.printStackTrace();
44 }
45 }
46
47 }
2
3 import java.io.DataInputStream;
4 import java.io.DataOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.ServerSocket;
9 import java.net.Socket;
10 import java.net.UnknownHostException;
11
12 import org.junit.Test;
13
14 public class TestTCP {
15 @Test
16 public void testTCPServer() {
17 try {
18 ServerSocket ss = new ServerSocket(9999);
19 while (true) {// 需要不断的监听是否有客户端程序连接上来,所以需要不断地监控
20 Socket socket = ss.accept();//阻塞式方法
21 InputStream is = socket.getInputStream();
22 DataInputStream dis = new DataInputStream(is);
23 System.out.println(dis.readUTF());
24 }
25 } catch (IOException e) {
26 e.printStackTrace();
27 }
28 }
29
30 @Test
31 public void testTCPClient() {
32 try {
33 Socket client = new Socket("127.0.0.1", 9999);
34 OutputStream os = client.getOutputStream();
35 DataOutputStream dos = new DataOutputStream(os);
36 dos.writeUTF("Hello Server");
37 dos.flush();
38 dos.close();
39
40 } catch (UnknownHostException e) {
41 e.printStackTrace();
42 } catch (IOException e) {
43 e.printStackTrace();
44 }
45 }
46
47 }