server代码
package cn.ant.demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
//使用Socket进行网络通信
static ServerSocket server = null;
//基于字节流
static InputStream in = null;
static OutputStream out = null;
public static void main(String[] args) {
try {
server = new ServerSocket(8000);
System.out.println("服务端启动成功,监听端口为8000,等待客户端连接...");
// while (true){
// TODO Auto-generated method stub
Socket socket = server.accept(); //等待客户端连接
System.out.println("客户连接成功,客户信息为:" +socket.getRemoteSocketAddress());
in = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
//读取客户端的数据
while ((len = in.read(buffer)) > 0) {
System.out.println(new String(buffer, 0, len));
}
//向客户端写数据
out = socket.getOutputStream();
out.write("hello!".getBytes());
// }
} catch (IOException e) {
e.printStackTrace();
}
}
}
client代码
package cn.ant.demo;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
//创建套接字对象socket并封装ip与port
Socket socket = new Socket("127.0.0.1", 8000);
//根据创建的socket对象获得一个输出流
//基于字节流
OutputStream outputStream = socket.getOutputStream();
//控制台输入以IO的形式发送到服务器
System.out.println("TCP连接成功 \n请输入:");
String str = new Scanner(System.in).nextLine();
byte[] car = str.getBytes();
outputStream.write(car);
System.out.println("TCP协议的Socket发送成功");
//刷新缓冲区
outputStream.flush();
//关闭连接
socket.close();
}
}
IO阻塞问题
只有一个用户请求时
有多个用户请求时
出现阻塞问题,第二个请求因阻塞未被及时处理
线程处理IO阻塞问题
注意:开启线程处理IO阻塞问题,并不是最好的,这只能解决,低并发问题,并且开启线程会大量消耗CUP资源.