作者:李程VS_328_302 | 来源:互联网 | 2023-10-11 11:29
学习时间
2021-04-07
学习内容
注意:本文在同一台机器上演示
测试类1:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;public class Test1 {public static void main(String[] args) throws IOException {TCPClient();}public static void TCPClient() throws IOException {Socket socket = new Socket("192.168.1.xxx", 2222);OutputStream outputStream = socket.getOutputStream();Scanner scanner = new Scanner(System.in);System.out.println("请输入要发送的内容:");String s = scanner.nextLine();outputStream.write(s.getBytes());socket.close();TCPServerClient();}public static void TCPServerClient() throws IOException {ServerSocket serverSocket = new ServerSocket(3333);Socket accept = serverSocket.accept();InputStream inputStream = accept.getInputStream();byte[] bytes = new byte[1024];int read = inputStream.read(bytes);String s = new String(bytes, 0, read);String ip = accept.getInetAddress().getHostAddress();System.out.println(ip + "发来信息:" + s);serverSocket.close();TCPClient();}
}
测试类2:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;public class Test2 {public static void main(String[] args) throws IOException {TCPServerClient();}public static void TCPClient() throws IOException {Socket socket = new Socket("192.168.1.xxx", 3333);OutputStream outputStream = socket.getOutputStream();Scanner scanner = new Scanner(System.in);System.out.println("请输入要发送的内容:");String s = scanner.nextLine();outputStream.write(s.getBytes());socket.close();TCPServerClient();}public static void TCPServerClient() throws IOException {ServerSocket serverSocket = new ServerSocket(2222);Socket accept = serverSocket.accept();InputStream inputStream = accept.getInputStream();byte[] bytes = new byte[1024];int read = inputStream.read(bytes);String s = new String(bytes, 0, read);String ip = accept.getInetAddress().getHostAddress();System.out.println(ip + "发来信息:" + s);serverSocket.close();TCPClient();}
}
声明:
关于转载:
允许非商业用途转载,注明出处和链接即可。