服务端流程:
服务端(Server.java):
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
//创建ServerSocket实例
serverSocket = new ServerSocket();
//绑定端口
serverSocket.bind(new InetSocketAddress(6666));
System.out.println("服务端启动成功啦");
//等待客户端的连接:accept(),获取用户的连接是socket,进行读写操作的是socket,不是ServerSocket
Socket socket = serverSocket.accept();
System.out.println("有客户端连接啦");
//读写操作,获取客户端的输出流
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[100];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
System.out.println("客户端发送消息:"+new String(bytes,0,len));
}
System.out.println("服务端关闭啦");
//关闭资源
socket.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客户端的流程:
客户端(Client.java):
public class Client {
public static void main(String[] args) {
Socket socket = null;
try {
//创建socket实例
socket = new Socket();
//连接服务端 :connect
socket.connect(new InetSocketAddress("127.0.0.1", 6666));
System.out.println("连接服务端成功");
//读写操作
OutputStream outputStream = socket.getOutputStream();
outputStream.write("网络编程".getBytes());
System.out.println("客户端已发送数据");
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (socket != null) {
try {
System.out.println("关闭资源");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
以上都是学习过程中的总结,会持续更新,如果有错误或者有疑问,欢迎一起交流吖~~
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_45981295/article/details/121416202
内容来源于网络,如有侵权,请联系作者删除!