目标
理解什么是BIO,了解的BIO的限制
了解
BIO : block I/O , 同步阻塞式,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销
限制:并发太多服务器会挂掉,只要并发到1000上下响应请求就会很慢
核心代码
服务端
public void createLink() {
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("服务端已启动");
Socket client = null;
while (true) {
System.out.println("BIO服务连接监听中...");
client = ss.accept();
System.out.println("客户端"+client.getInetAddress().getLocalHost()+"已连接到服务器");
doSomething(client);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void doSomething(Socket client) {
InputStream in = null;
OutputStream os = null;
try {
in = client.getInputStream();
byte[] buff = new byte[1024];
int len = in.read(buff);
if (len > 0) {
String msg = new String(buff, 0, len);
System.out.println("客户端发送了信息:"+msg);
os = client.getOutputStream();
os.write("同步阻塞式服务".getBytes());
System.out.println("已向客户端返回信息!");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if(null!=in) in.close();
if(null!=os) {
os.flush();
os.close();
}
if(null!=client) {
client.close();
client = null;
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
客户端
public void createClient() {
Socket s = null;
try {
s = new Socket("127.0.0.1", 8888);
System.out.println("服务器连接成功...");
doSomething(s);
} catch (ConnectException e) {
System.err.println("服务器连接失败...");
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if(null!=s) s.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void doSomething(Socket s) {
InputStream is = null;
OutputStream os = null;
try {
if (null!=s) {
os = s.getOutputStream();
os.write("SocketClient1".getBytes());
is = s.getInputStream();
byte[] buff = new byte[1024];
int len = is.read(buff);
if (len > 0) {
String msg = new String(buff, 0, len);
System.out.println("服务端返回信息:"+msg);
}else {
System.out.println("未获取到服务端返回的信息!");
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if(null!=is)is.close();
if(null!=os) {
os.flush();
os.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}