0
点赞
收藏
分享

微信扫一扫

TCP聊天功能demo

慎壹 2022-03-24 阅读 34


客户端

1,连接服务器socket

2,发送消息

public static void main(String[] args) {
Socket socket = null;
OutputStream outputStream = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 10000);
outputStream = socket.getOutputStream();
outputStream.write("您好".getBytes());
} catch (Exception 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();
}
}
}
}

服务端

1,建立服务端口ServerSocket

2,等待客户端连接accept

3,接收消息

public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
// byte[] buffer = new byte[1024];
// int len;
// while ((len = inputStream.read()) != -1) {
// String msg = new String(buffer, 0, len);
// System.out.println(msg);
// }
serverSocket = new ServerSocket(10000);
//客户端重复启动,服务端可以一直接收
while (true){
//等待客户端连接
socket = serverSocket.accept();
//读取客户端消息
inputStream = socket.getInputStream();

//1,创建管道/
byteArrayOutputStream = new ByteArrayOutputStream();

//2,创建Buffer
byte[] buffer = new byte[1024];
//ByteBuffer buffer = ByteBuffer.allocate(1024);

//3,读取数据到Buffer
int read;
while ((read = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, read);
}
System.out.println(byteArrayOutputStream.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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();
}
}
}
}

结果

TCP聊天功能demo_网络



举报

相关推荐

0 条评论