TCP传输:服务器给客户端一个反馈案例
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public classServerDemo {
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象
ServerSocketss = newServerSocket(9999);
// 监听客户端的连接
Sockets = ss.accept(); // 阻塞
// 获取输入流
InputStreamis = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys); // 阻塞
Stringserver = newString(bys, 0, len);
System.out.println("server:"+ server);
// 获取输出流
OutputStreamos = s.getOutputStream();
os.write("数据已经收到".getBytes());
// 释放资源
s.close();
// ss.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public classClientDemo {
public static void main(String[] args) throws IOException {
// 创建客户端Socket对象
Sockets = newSocket("219.216.80.19", 9999);
// 获取输出流
OutputStreamos = s.getOutputStream();
os.write("今天天气很好,适合睡觉".getBytes());
// 获取输入流
InputStreamis = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);// 阻塞
Stringclient = newString(bys, 0, len);
System.out.println("client:"+ client);
// 释放资源
s.close();
}
}