![2cf0cb4e7a23b1302d119e089f4c3438.png](https://i-blog.csdnimg.cn/blog_migrate/ee5d833356c2b7ed6a010816e2f2f0c2.jpeg)
一次简单的通信测试
/**
* 客户端
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
//创建socket对象
Socket client = new Socket("192.168.143.177",9999);
//获取输入流
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeUTF("hehehehehhehehehehehex");
//获取输入流
DataInputStream is = new DataInputStream(client.getInputStream());
System.out.println(is.readUTF());
//关闭
if(is!=null) {
is.close();
}
if(os!=null) {
os.close();
}
if(client!=null) {
client.close();
}
}
}
/**
* 服务器端
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) throws IOException {
System.out.println("-------------服务器启动----------------");
//1创建ServerSocket对象
ServerSocket ss = new ServerSocket(9999);
//监听是否有客户端来请求
Socket client = ss.accept();
//获取输入流
DataInputStream is = new DataInputStream(client.getInputStream());
System.out.println(is.readUTF());
//获取输入流
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeUTF("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
//关闭流,关闭Socket
if(os!=null) {
os.close();
}
if(is!=null) {
is.close();
}
if(ss!=null) {
ss.close();
}
}
}
/**
* 服务器端
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) throws IOException {
System.out.println("-------------服务器启动----------------");
//1创建ServerSocket对象
ServerSocket ss = new ServerSocket(9999);
//监听是否有客户端来请求
Socket client = ss.accept();
//获取输入流
DataInputStream is = new DataInputStream(client.getInputStream());
System.out.println(is.readUTF());
//获取输入流
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeUTF("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
//关闭流,关闭Socket
if(os!=null) {
os.close();
}
if(is!=null) {
is.close();
}
if(ss!=null) {
ss.close();
}
}
}
运行效果
![95434b66f9b5da06437717b2525147a7.png](https://i-blog.csdnimg.cn/blog_migrate/07da7e01cb2f86bb5215c0546e6d9ecf.jpeg)