是否有任何小型工作程序可用于使用java nio从客户端接收数据并向客户端发送数据。
实际上我无法写入套接字 channel ,但是我可以读取传入的数据
如何将数据写入套接字 channel
谢谢
迪帕克
最佳答案
您可以像这样将数据写入套接字 channel :
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class SocketWrite {
public static void main(String[] args) throws Exception{
// create encoder
CharsetEncoder enc = Charset.forName("US-ASCII").newEncoder();
// create socket channel
ServerSocketChannel srv = ServerSocketChannel.open();
// bind channel to port 9001
srv.socket().bind(new java.net.InetSocketAddress(9001));
// make connection
SocketChannel client = srv.accept();
// UNIX line endings
String response = "Hello!\n";
// write encoded data to SocketChannel
client.write(enc.encode(CharBuffer.wrap(response)));
// close connection
client.close();
}
}
InetSocketAddress可能会有所不同,具体取决于您要连接的对象。