您的位置:首页 > 其它

Socket —— 发送端与接收端通过 io 交互

2016-07-24 00:06 309 查看
这一节的例子,TCP 客户端要接收返回。

public class ClientDemo {

public static void main(String[] args) throws IOException {
// 创建客户端 Socket 连接
Socket socket = new Socket("192.168.100.112",8889);
// 获取输出流
OutputStream os =  socket.getOutputStream();
os.write("今天是个好日子".getBytes());

// 获取输入流,读取服务端返回的数据
InputStream is = socket.getInputStream();
byte[] bys = new byte[1024];
// 阻塞
Integer len = is.read(bys);
String data = new String(bys,0,len);

System.out.println("服务端返回的数据是:" + data);
// 释放资源
socket.close();
}

}


服务端(接收端)代码:

public class ServerDemo {

public static void main(String[] args) throws IOException {
// 创建服务端 ServerSocket 对象
ServerSocket ss = new ServerSocket(8889);
// 监听客户端连接
// 阻塞
Socket s = ss.accept();
// 获取输入流
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
// 阻塞
Integer len = is.read(bys);
String data = new String(bys,0,len);
System.out.println("接收到的数据 => " + data);

// 获取输出流
OutputStream os = s.getOutputStream();
os.write("数据已经收到。" .getBytes());
s.close();
// ss.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  socket