Socket基础

服务端

 

public class MyService {
public static void main(String[] args) throws IOException {
ServerSocket socketService = new ServerSocket(9999);
Socket socket = socketService.accept();
System.out.println("等待客户端连接");
InputStream inputStream = socket.getInputStream();
byte[] ss=new byte[1024];
inputStream.read(ss);
System.out.println("接收到客户端的数据"+new String(ss));

//向客户端发起反馈
OutputStream out = socket.getOutputStream();
out.write("我已接受到你的信息".getBytes());
out.close();
inputStream.close();
socket.close();


}
}
客户端
public class MyClient {
public static void main(String[] args) throws IOException {
InetAddress address = InetAddress.getByName("127.0.0.1");
Socket socket = new Socket(address,9999);
OutputStream outputStream = socket.getOutputStream();
String ss="Hello";
outputStream.write(ss.getBytes());
//获取服务端反馈的消息
InputStream in = socket.getInputStream();
byte[] s=new byte[1024];
in.read(s);
System.out.println("获取到反馈的消息"+new String(s
));
outputStream.close();
in.close();
socket.close();


}
}
posted @ 2021-11-16 20:10  yydssc  阅读(25)  评论(0)    收藏  举报