#java #sockets #io #nio #grizzly
Вопрос:
Я новичок в Grizzly и столкнулся с проблемой при создании простого эхо-сервера/клиента в Grizzly. Код для сервера Echo используется из примеров, приведенных в руководстве Grizzly.
Эхо-сервер
public class EchoServer {
public static final String HOST = "localhost";
public static final int PORT = 7777;
public static void main(String[] args) throws IOException {
FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless();
filterChainBuilder.add(new TransportFilter());
// StringFilter is responsible for Buffer <-> String conversion
filterChainBuilder.add(new StringFilter(Charset.forName("UTF-8")));
// EchoFilter is responsible for echoing received messages
filterChainBuilder.add(new EchoFilter());
// Create TCP transport
final TCPNIOTransport transport = TCPNIOTransportBuilder.newInstance().build();
transport.setProcessor(filterChainBuilder.build());
try {
// binding transport to start listen on certain host and port
transport.bind(HOST, PORT);
// start the transport
transport.start();
logger.info("Press any key to stop the server...");
System.in.read();
} finally {
logger.info("Stopping transport...");
// stop the transport
transport.shutdownNow();
logger.info("Stopped transport...");
}
}
}
Эхофильтр
TCP-клиент
public class EchoClient {
private String host="localhost";
private int port=7777;
private Socket socket;
public EchoClient()throws IOException {
socket=new Socket(host,port);
//Get the port number after binding and the port number before binding
System.out.println("new Connecttion accept" socket.getInetAddress() ":" socket.getPort() ",localPort:" socket.getLocalPort());
}
private PrintWriter getWriter(Socket socket) throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket)throws IOException{
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void talk() throws IOException{
try{
BufferedReader br=getReader(socket);
PrintWriter pw=getWriter(socket);
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String msg=null;
while((msg=reader.readLine())!=null){
pw.println(msg);
pw.flush();
System.out.println(br.readLine());
if(msg.equals("bye")){
break;
}
}
}catch(IOException e){
e.printStackTrace();
}
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException{
new EchoClient().talk();
}
}
Connection seems to be established but somehow Server is not reading the data send by client
Output on server side
Jun 12, 2021 5:24:35 PM framework.grizzly.EchoServer main
INFO: Press any key to stop the server…