TCP聊天
步骤:
服务端:
- 创建服务端
- 创建服务端口
- 等待客户端连接
- 接收客户端发送的数据
客户端:
- 创建客户端
- 获取服务端ip地址
- 获取服务端口
- 连接并且发送数据
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
serverSocket = new ServerSocket(5678);
while (true){
socket = serverSocket.accept();
inputStream = socket.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len=inputStream.read(bytes))!=-1){
byteArrayOutputStream.write(bytes,0,len);
}
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();
}
}
}
}
}
public class TcpClient {
public static void main(String[] args) {
Socket socket=null;
OutputStream outputStream=null;
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 5678;
socket = new Socket(serverIP,port);
outputStream = socket.getOutputStream();
outputStream.write("Hello".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException 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();
}
}
}
}
}
运行结果:
Hello
Hello
Hello
注意:先启动服务器,再启动客户端
TCP和UDP的区别
TCP协议:面向连接的协议,连接成功后再发送数据,类似打电话,等待对方接通才能通话。
UDP协议:无连接协议,类似发短信,知道手机号就可以发送,有可能会接收不到数据。
|