java通过TCP实现网络聊天
什么是TCP(传输控制协议)?传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议而对于tcp网络聊天而言,首先我们需要先建立连接,只有在建立连接之后,我们才能够通过tcp进行数据传输。客户端:public class Client_work {public static void main(String[] arg
·
什么是TCP(传输控制协议)?
传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议
而对于tcp网络聊天而言,首先我们需要先建立连接,只有在建立连接之后,我们才能够通过tcp进行数据传输。
客户端:
public class Client_work {
public static void main(String[] args) {
OutputStream outputStream=null;
Socket socket=null;
//1.我们客户端向服务端发送数据,首先需要知道服务端的ip和端口号
InetAddress byName=null;
try {
byName = InetAddress.getByName("127.0.0.1");
int port=9999;
//2.创建一个socket连接
socket = new Socket(byName,port);
//3.发送消息,通过io流
outputStream = socket.getOutputStream();
outputStream.write("mysql".getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
outputStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
服务端:
public class Server_work {
public static void main(String[] args) {
ServerSocket serverSocket=null;
InputStream inputStream=null;
Socket accept=null;
try {
//1.服务端需要有一个地址来接收数据
serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
accept = serverSocket.accept();
//3.把连接过来获取的socket数据进行读取
inputStream = accept.getInputStream();
//4.通过管道流把读取到的数据写出来
byte[] bs=new byte[1024];
int len;
while ((len=inputStream.read(bs))!=-1){
String s = new String(bs, 0, len);
System.out.println(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
inputStream.close();
accept.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
服务端执行成功:

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)