public class TcpTest {
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
try {
//1、创建Socket对象,指明服务器端的ip和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,8899);
//2、获取输出流对象,用于输出数据
os = socket.getOutputStream();
//3、开始写数据
os.write("你好!我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
使用TCP通信案例一:客户端发消息给服务端,服务端将数据显示在控制台
最新推荐文章于 2023-06-24 11:36:41 发布