TCP实现聊天
TCP实现聊天
客户端:
- 连接服务器 Socket
- 发送消息
服务器端:
- 建立服务器端口 ServerSocket
- 等待连接 accept
- 接收用户的消息
// TcpClientDemo01.java
package com.example.network;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
// 获取ip
InetAddress serviceIp = InetAddress.getByName("localhost");
int port = 9999;
// 创建连接
socket = new Socket(serviceIp, port);
// 输出流
os = socket.getOutputStream();
// 向输出流里面写
os.write("坚持学习java".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} 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();
}
}
}
}
}
// TcpServiceDemo01.java
package com.example.network;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServiceDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
// 创建一个地址
serverSocket = new ServerSocket(9999);
while (true) {
// 等待连接
socket = serverSocket.accept();
// 获取输入流
is = socket.getInputStream();
// 管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
// 写入管道流
baos.write(buffer, 0, len);
}
System.out.println(baos);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.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();
}
}
}
}
}