你能给我展示一个使用java nio进行通信的客户端和服务器的本地主机的小例子吗?我需要了解它是如何工作的java nio。例如: 1)客户端需要连接,客户端连接客户端发送"Hello i'm a client“。2)服务器接受,服务器接收来自客户端的消息,服务器响应"hello i'm a server“3)客户端发送"hello server”4)服务器发送"hello client“。
我不需要服务器同时处理多个客户端,我需要了解的是客户端和服务器之间的多消息连接是如何发生的。
发布于 2018-11-23 04:57:31
发布于 2018-11-23 05:07:58
如果不打算处理多个连接,我真的不确定为什么需要使用nio。我看不出使用它们有什么意义。
好的,现在开始:让我知道这是否有效。
服务器代码:
public class Server {
ServerSocket socket;
Socket listener;
public Server(int port) throws IOException {
socket = new ServerSocket(port);
}
public void connect() throws IOException{
listener = socket.accept();
}
public String read() throws IOException{
byte[] temp = new byte[1024];
int bytesRead = 0;
try(InputStream input = listener.getInputStream()){
bytesRead = input.read(temp);
}
return new String(temp,0,bytesRead,"ASCII");
}
public void write(String data) throws IOException{
byte[] temp = new byte[1024];
try(OutputStream out = listener.getOutputStream()){
out.write(data.getBytes());
out.flush();
}
}
public void close(){
socket.close();
}
}客户端代码:
public class Client{
Socket client;
InetSocketAddress addr;
public Client(String ip, int port) throws IOException{
client = new Socket();
addr = new InetSocketAddress(ip,port);
}
public void connect() throws IOException{
client.connect(addr);
}
public String read() throws IOException{
byte[] temp = new byte[1024];
int bytesRead = 0;
try(InputStream input = client.getInputStream()){
bytesRead = input.read(temp);
}
return new String(temp,0,bytesRead,"ASCII");
}
public void write(String data) throws IOException{
byte[] temp = new byte[1024];
try(OutputStream out = client.getOutputStream()){
out.write(data.getBytes());
out.flush();
}
}
public void close(){
client.close();
}
}现在,您所要做的就是在服务器上调用connect(),然后在客户端上调用connect(),并编写和发送所需的消息。
完成所有操作后,不要忘记调用close。
还要注意的是,您需要一些机制来告诉服务器和客户端每条消息有多长。或者,您可以指定一个结束字符来告诉客户端/服务器消息已结束。
服务器中的一次发送不一定等于客户端中的一次读取,反之亦然。你将不得不弄清楚该怎么做。
https://stackoverflow.com/questions/53437871
复制相似问题