TCP通讯的两个应用程序:服务端和客户端
TCP和UDP的区别
- TCP通讯可靠但效率低(需要连接)
- UDP通讯不可靠但效率高(不需要连接)
socket
- socket是设备通信的端点,socket可以让程序将网络连接当成流,数据通过socket进行io操作
- 个人理解:socket (套间字)是设备通信的端点,socket通过网络连接通道进行i o操作。
(此处应有图)
TCP字节流编程
- 服务端负责监听端口(ServerSocket)并等待连接(ServerSocket.accept)
- 客户端负责连接服务端( new Socket(InetAddress+端口号) )
- 连接成功后通过socket进行io传输
- 注意点
- 端口只能被一个服务端监听
- 服务端可以与多个客户端监听
- 传输完毕后要关闭流
- 输出完数据结束后要设置结束标记
- 代码实现
1.服务端
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4399);
System.out.println("服务器端监听中");
Socket socket = serverSocket.accept();
System.out.println("连接成功");
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int readlen = 0;
while ((readlen = inputStream.read(b)) != -1){
System.out.println(new String(b,0,readlen));
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new String("hello,client").getBytes());
socket.shutdownOutput();
System.out.println("关闭流 退出噜");
serverSocket.close();
socket.close();
inputStream.close();
outputStream.close();
}
2.客户端
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getLocalHost(), 4399);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new String("hello,server").getBytes());
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int readlen = 0;
while ((readlen = inputStream.read(b)) != -1){
System.out.println(new String(b,0,readlen));
}
socket.close();
outputStream.close();
inputStream.close();
}
TCP字节流编程
- 服务端负责监听端口(ServerSocket)并等待连接(ServerSocket.accept)
- 客户端负责连接服务端( new Socket(InetAddress+端口号) )
- 连接成功后通过socket进行io传输
- 注意点
- 端口只能被一个服务端监听
- 服务端可以与多个客户端监听
- 传输完毕后要关闭流
- 输出完数据结束后要设置结束标记(socket.shutdown()也可以用bufferedWriter.newLine() )
- 如果使用newLine()作为结束标记 对方需要用readline()接收数据
- 代码实现
-
- 服务端
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器端监听中");
Socket socket = serverSocket.accept();
System.out.println("连接成功");
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s;
while ((s=bufferedReader.readLine()) != null){
System.out.println(s);
}
System.out.println("关闭流 退出噜");
serverSocket.close();
socket.close();
bufferedReader.close();
}
2.客户端
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("hello,小黄");
bufferedWriter.newLine();
bufferedWriter.write("hello,小黄");
bufferedWriter.flush();
bufferedWriter.newLine();
System.out.println("关闭流 退出噜");
bufferedWriter.close();
socket.close();
}
|