是否有任何小型工作程序可以使用 java nio 从客户端接收数据并向客户端发送数据。
实际上我无法写入套接字通道,但我能够读取传入的数据
如何向socket通道写入数据
谢谢
迪帕克
您可以将数据写入套接字通道,如下所示:
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();
}
}
The InetSocket地址可能会有所不同,具体取决于您连接的内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)