如果您不打算处理多个连接,则不确定为什么需要使用 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。
另外请注意,您将需要一些机制来告诉服务器和客户端每条消息将持续多长时间。或者您可以指定一个结束字符,告诉客户端/服务器消息已经结束。
服务器中的一次发送不一定等于客户端中的一次读取,反之亦然。你将不得不弄清楚该怎么做。