Java利用TCP读取并发送数据
作者:
Agoni7z
,
2024-05-07 21:24:45
,
所有人可见
,
阅读 15
Server
package com.itheima.A05TCP_demp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
// TCP协议,接收数据
// 1, 创建对象ServerSocket
ServerSocket ss = new ServerSocket(10000);
// 2. 监听客户端连接
Socket socket = ss.accept();
// 3. 从连接通道中获取输入流
/*InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is); // 创建转换流 避免中文乱码
BufferedReader br = new BufferedReader(isr);*/
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int b;
while ((b = br.read()) != -1) {
System.out.print((char) b);
}
// 4. 释放资源
socket.close();
ss.close();
}
}
Client
package com.itheima.A05TCP_demp1;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
//TCP协议,发送数据
//1. 创建Socket对象
//细节:在创建对象的同时会连接服务器
// 如果连接不上 代码会报错
Socket socket = new Socket("127.0.0.1",10000);
// 2.从连接通道中获取输出流
OutputStream os = socket.getOutputStream();
// 写出数据
os.write("你好你好".getBytes());
//3. 释放资源
os.close();
socket.close();
}
}