package com.stream;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Network2 {
//客户端发送信息给服务端,服务端将数据显示在控制台上
@Test
public void client() {
Socket socket = null;
OutputStream outputStream = null;
try {
//对方的IP
InetAddress ip = InetAddress.getByName("172.20.10.6");
socket = new Socket(ip, 8187);
outputStream = socket.getOutputStream();
outputStream.write("你好我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
// //关闭资源
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
//1、创建服务器端的ServerSocket,指明自己的端口号
serverSocket = new ServerSocket(8187);
//2、接收来自客户端的socket
socket = serverSocket.accept();
//3、获取输入流
inputStream = socket.getInputStream();
//4、读取输入流中的数据
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[20];
int len;
while ((len = inputStream.read(buffer)) != -1) {
//将字节存储在数组中
byteArrayOutputStream.write(buffer, 0, len);
}
//调用toString()
System.out.println(byteArrayOutputStream.toString());
System.out.println("收到了"+socket.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
用Java模拟TCP网络编程
最新推荐文章于 2023-07-25 14:22:22 发布