TCP实现聊天
2024-10-20 11:54:59
TCP实现聊天
IO流关闭是简写的,正常写要判断是否为null
客户端:(最好捕获异常)
1.连接服务器Socket
2.发送消息
package net.TCPChat;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
// 客户端
public class TcpClientDemo01 {
public static void main(String[] args) throws IOException {
//1.要知道服务器的地址
InetAddress serverIp=InetAddress.getByName("127.0.0.1");
//2.端口号
int port = 9999;
//3.创建socket连接
Socket socket = new Socket(serverIp, port);
//4.发送消息 IO流
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好,欢迎学习".getBytes());
outputStream.close();
socket.close();
}
}
服务器:(最好捕获异常)
1.建立服务的端口:ServerSocket
2.等待用户的连接:accept
3.接收用户的消息
public static void main(String[] args) throws IOException {
//1.我要有一个地址
ServerSocket serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
Socket accept = serverSocket.accept();
//3.读取客户端的消息
InputStream inputStream = accept.getInputStream();
//管道流
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
baos.close();
inputStream.close();
accept.close();
serverSocket.close();
}
最新文章
- 特征检测之Haar
- Linux之head、tail、grep、cut等命令详解
- Windows Azure HandBook (3) 浅谈Azure安全性
- globals()
- Oracle corrupt block(坏块) 详解
- Real-Rime Rendering (2) - 变换和矩阵(Translation and Matrics)
- rsyslog同步history日志(转载)
- .net 和java JSON 模板
- XNA 4.0 环境搭建和 Hello World,Windows Phone 游戏开发
- apache bench(ab)压力测试模拟POSt请求
- EditText光标居上
- 如何用Math.max.apply()获取数组最大/小值
- p12文件和mobileprovision文件
- hive入门学习线路指导
- windows server 2008 R2安装图片浏览器/照片查看器方法
- Java代理和动态代理机制分析和应用
- html5-css边框img
- String [] args是干什么的
- CodeForces 651 C Watchmen
- maven 统一管理依赖的版本号