1.客户端
公司产品的客户端的使用阻塞式的Socket,并没有使用NIO,在Hadoop中遇到再议。
2.服务器端
2.1 阻塞式
例子程序
public class BIOServer {
static class Hanlder extendsThread {
privateSocket socket;
publicHanlder(Socket socket) {
this.socket= socket;
}
@Override
public void run(){
try {
InputStream in = socket.getInputStream();
BufferedReader brIn = new BufferedReader(newInputStreamReader(in));
OutputStream out =socket.getOutputStream();
out.write(("login: " + new Date() + "
").getBytes());
while (true) {
//线程在此阻塞,直到读到客户端新的数据
String cmd =brIn.readLine();
System.out.println("receive:" + cmd + "
");
out.write(("return: " + cmd.toUpperCase() +"
").getBytes());
if("bye".equalsIgnoreCase(cmd)) {
out.write(("logout: " + newDate() + "
").getBytes());
break;
}
}
socket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
publicstatic void main(String[] args) {
try {
ServerSocket serverSocket =
newServerSocket(7777);
while (true) {
//线程在此阻塞,直到收到新的连接
Socket socket =serverSocket.accept();
//对每个连接使用一个线程进行处理
new Hanlder(socket).start();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
2.2 非阻塞式