如何将数据写入套接字通道

是否有任何小工作程序用于使用java nio从客户端接收和发送数据。

实际上我无法写入套接字通道,但我能够读取传入的数据如何将数据写入套接字通道

谢谢迪帕克

您可以将数据写入套接字通道,如下所示:

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可能会根据您连接的内容而有所不同。