Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从NIO服务器发送消息_Java_Sockets_Nio - Fatal编程技术网

Java 从NIO服务器发送消息

Java 从NIO服务器发送消息,java,sockets,nio,Java,Sockets,Nio,下面的代码成功地创建了一个服务器并接受了一个传入的客户端 package socket; import java.nio.*; import java.nio.channels.*; import java.net.*; import java.util.*; import java.io.IOException; public class NonBlockingServer { public static void main(String[] args) throws Inter

下面的代码成功地创建了一个服务器并接受了一个传入的客户端

package socket;

import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.io.IOException;

public class NonBlockingServer {

    public static void main(String[] args) throws InterruptedException, IOException {

        // Create a new Thread
        Server s = new Server();
        new Thread(s).start();

        // Give 10 seconds for client to connect
        Thread.sleep(10000);

// This Doesn't work?

        s.Write("Hello, Client!");

        System.out.println("Done");
    }
}

//A class which implements Runnable Interface
class Server implements Runnable  {

    SocketChannel AcceptedClient;
    ServerSocketChannel serverChannel;
    Selector selector;

    void Write(String s) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(s.length());
        buffer.put(s.getBytes());

        int numWrite = -1;
        numWrite = AcceptedClient.write(buffer);

        while (buffer.hasRemaining())
        {
            numWrite += AcceptedClient.write(buffer);
        }

        System.out.println(numWrite);
    }

    @Override
    public void run()
    {

        int port = 4041;

        System.out.println("Listening for connections on port " + port);

        try {
            // Bind the port
            serverChannel = ServerSocketChannel.open();
            ServerSocket ss = serverChannel.socket();
            InetSocketAddress address = new InetSocketAddress(port);
            ss.bind(address);

            // Non-blocking Server
            serverChannel.configureBlocking(false);

            // Register with Selector
            selector = Selector.open();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException ex) {
            ex.printStackTrace();
            return;
        }

        while (true) {

            try {

                // Blocks until a 'socket' is ready registered with selector is ready.
                selector.select();

            } catch (IOException ex) {
                ex.printStackTrace();
                break;
            }

            Set<SelectionKey> readyKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = readyKeys.iterator();

            while (iterator.hasNext()) {

                SelectionKey key = iterator.next();
                iterator.remove();

                try {

                    if (key.isAcceptable()) {

                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        SocketChannel client = server.accept();
                        System.out.println("Accepted connection from " + client);
                        client.configureBlocking(false);

                        // Client accepted by server can read.
                        SelectionKey key2 = client.register(selector, SelectionKey.OP_READ);

                        AcceptedClient = (SocketChannel) key2.channel();

                    }

                } catch (IOException ex) {
                    key.cancel();
                    try {
                        key.channel().close();
                    } catch (IOException cex) {
                    }
                }
            }
        }
    }
} 
封装插座;
导入java.nio.*;
导入java.nio.channels.*;
导入java.net。*;
导入java.util.*;
导入java.io.IOException;
公共类非阻塞服务器{
公共静态void main(字符串[]args)引发InterruptedException、IOException{
//创建一个新线程
服务器s=新服务器();
新线程。开始();
//给客户端10秒时间进行连接
睡眠(10000);
//这不管用?
s、 写下(“你好,客户!”);
系统输出打印项次(“完成”);
}
}
//实现可运行接口的类
类服务器实现可运行{
SocketChannel接受客户端;
serversocketchannelserverchannel;
选择器;
无效写入(字符串s)引发IOException{
ByteBuffer buffer=ByteBuffer.allocate(s.length());
buffer.put(s.getBytes());
int numWrite=-1;
numWrite=AcceptedClient.write(缓冲区);
while(buffer.haslaining())
{
numWrite+=AcceptedClient.write(缓冲区);
}
System.out.println(numWrite);
}
@凌驾
公开募捐
{
int端口=4041;
System.out.println(“侦听端口上的连接”+端口);
试一试{
//绑定端口
serverChannel=ServerSocketChannel.open();
ServerSocket ss=serverChannel.socket();
InetSocketAddress地址=新的InetSocketAddress(端口);
ss.bind(地址);
//非阻塞服务器
serverChannel.configureBlocking(false);
//带选择器的寄存器
选择器=selector.open();
serverChannel.register(选择器、SelectionKey.OP_ACCEPT);
}捕获(IOEX异常){
例如printStackTrace();
回来
}
while(true){
试一试{
//阻止,直到“套接字”准备就绪并注册到选择器准备就绪。
selector.select();
}捕获(IOEX异常){
例如printStackTrace();
打破
}
设置readyKeys=selector.selectedKeys();
迭代器迭代器=readyKeys.Iterator();
while(iterator.hasNext()){
SelectionKey=iterator.next();
iterator.remove();
试一试{
if(key.isAcceptable()){
ServerSocketChannel server=(ServerSocketChannel)key.channel();
SocketChannel client=server.accept();
System.out.println(“接受来自“+客户端的连接”);
client.configureBlocking(false);
//服务器接受的客户端可以读取。
SelectionKey key2=客户端.寄存器(选择器,SelectionKey.OP_读取);
AcceptedClient=(SocketChannel)key2.channel();
}
}捕获(IOEX异常){
键。取消();
试一试{
key.channel().close();
}捕获(IOX异常){
}
}
}
}
}
} 
但当我尝试在连接到服务器后向客户端发送消息时,它不起作用,即客户端没有收到消息

从服务器向特定客户端发送消息的正确方式是什么

我查看了互联网,没有发现任何服务器向客户端发送消息的示例。

您需要在
写入()之前
翻转()
缓冲区,如果要保留缓冲区,则需要在之后
压缩()


注意:关闭频道会取消按键。

您看起来不是很努力。互联网上充满了NIO发送和接收示例。Java教程,首先,更不用说这个网站了。我已经回答了上百个问题。翻页后它工作了。谢谢你,EJP!我想知道,如果我想让服务器向所有连接的客户端广播消息,那么我会使用OP_WRITE吗?现在我遇到的更重要的问题是关于关闭ServerSocketChannel。它有一个线程、连接到服务器的客户端、选择器和服务器本身。请帮我开始关闭文件好吗?呃,
ServerSocketChannel.close()
SocketChannel.close()
,和
Selector.close()
?如果你有新问题,把它们当作新问题问。这不是一个论坛。