import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author
* @date 2021/4/2 19:42
*/
public class TCPTest {
// 客户端
@Test
public void client(){
Socket socket= null;
OutputStream outputStream= null;
try {
// 创建socket对象,端口号为8848自定义,并指明ip地址
InetAddress net=InetAddress.getByName("127.0.0.1");
socket = new Socket(net,8848);
// 获取输出流,准备传输
outputStream = socket.getOutputStream();
// 写入信息
outputStream.write("hello world".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;
try {
// 创建服务器的serversocket,指明自己的端口号
serverSocket = new ServerSocket(8848);
// 调用accept,接收客户端的socket
socket = serverSocket.accept();
// 获取输入流
inputStream = socket.getInputStream();
// 读取输入流数据
byte[] bytes=new byte[1024];
int len;
while ((len=inputStream.read(bytes))!=-1){
String s=new String(bytes,0,len);
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
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();
}
}
}
}
}