كيفية كتابة البيانات إلى قناة المقبس
سؤال
هل هناك أي برنامج عمل صغير لاستلام البيانات وإرسالها إلى العميل باستخدام Java NIO.
في الواقع ، أنا غير قادر على الكتابة إلى قناة Socket ، لكنني قادر على قراءة البيانات الواردة كيفية كتابة البيانات إلى قناة Socket
شكرا ديباك
المحلول
يمكنك كتابة البيانات إلى قناة مقبس مثل SO:
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 قد تختلف حسب ما تتصل به.
لا تنتمي إلى StackOverflow