我有下面的javanio服务器,下面是python asyncore 客户。服务器打印“已接受…\n”,但是,客户端的 从不调用handle连接。有人能帮我解决什么问题吗 帮助我用客户端连接服务器?在
Java NIO服务器:
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.Selector;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
class Server
{
public Selector sel;
public ServerSocketChannel ssc;
public SocketChannel channel;
public static void main(String[] args) throws Exception
{
Server s = new Server();
s.openSocket(12000);
s.run();
}
private void openSocket(int port) throws Exception
{
InetSocketAddress address = new InetSocketAddress("0.0.0.0", port);
ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().bind(address);
sel = Selector.open();
ssc.register(sel, SelectionKey.OP_ACCEPT);
}
public void run() throws Exception
{
while (true)
{
sel.select();
Set<SelectionKey> keys = sel.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while (i.hasNext())
{
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (!key.isValid())
{
continue;
}
if (key.isAcceptable())
{
channel = ssc.accept();
channel.configureBlocking(false);
System.out.println("Accepted...\n");
channel.register(sel, SelectionKey.OP_READ);
}
if (key.isReadable())
{
if (channel == key.channel())
{
System.out.println("Readable\n");
ByteBuffer buffer = ByteBuffer.wrap(new byte[1024]);
int pos = channel.read(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, pos));
}
}
}
}
}
}
Python异步客户端:
^{pr2}$Python正常工作客户端:
# Echo client program
import socket
import sys
HOST = 'localhost' # The remote host
PORT = 12000 # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
print("socket")
except OSError as msg:
s = None
continue
try:
s.connect(sa)
print("connected")
except OSError as msg:
s.close()
s = None
continue
break
if s is None:
print('could not open socket')
sys.exit(1)
print("Sending")
s.sendall(bytes("Hey server", "UTF-8"))
data = s.recv(1024)
# s.close()
print('Received', repr(data))
EDIT添加了isReadable to Java,并添加了正常工作的python客户端。在
在实现一个冗长的asyncore方法时,您犯了两个错误:
此方法返回}永远不被认为是可写的。第二个错误是,您需要在尝试建立连接时检查可写性。由于
None
(因为您忘记了该语句的return
部分)。第一个错误是None
有一个错误的布尔值,因此{writable
始终返回false,包括在连接尝试期间,因此在建立连接方面没有任何进展。在我建议您改为签出Twisted。它并不能让你自己实现低级别的缓冲区管理和连接设置代码,因此实际上产生了更高效的代码,这些代码更短、更容易编写。在
asyncore应该被认为是一个历史性的产物,从来没有实际使用过。在
相关问题 更多 >
编程相关推荐