Java NIO服务器与Python asyncore客户端
我有一个Java NIO服务器,下面还有一个Python的asyncore客户端。服务器会打印“Accepted...\n”,但是客户端的handle_connect方法从来没有被调用过。有人能帮我看看服务器哪里出了问题,以及怎么用客户端连接到服务器吗?
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 asyncore客户端:
import socket
import select
import asyncore
class Connector(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.buffer = "hi"
self.create_socket()
self.connect((host, port))
def handle_connect(self):
print("[]---><---[]") # not called <------------------
def handle_read(self):
pass
def writable(self):
len(self.buffer) > 0
def handle_write(self):
sent = self.send(self.buffer)
print("[]--->" + self.buffer[0:sent])
self.buffer = self.buffer[sent:]
def handle_close(self):
print("[]...x...[]")
self.close()
connector = Connector("localhost", 12000, Handler())
asyncore.loop()
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))
编辑:我在Java中添加了isReadable,并且添加了正常工作的Python客户端。
1 个回答
1
你在实现一个麻烦的 asyncore 方法时犯了两个错误:
def writable(self):
len(self.buffer) > 0
这个方法返回的是 None
(因为你忘记加 return
这一部分了)。第一个错误是 None
的布尔值是假的,所以 Connector
永远不会被认为是可写的。第二个错误是你需要在尝试建立连接时检查是否可写。因为 writable
总是返回假,包括在连接尝试期间,所以连接根本没有进展。
我建议你看看 Twisted。这个库不需要你自己处理底层的缓冲区管理和连接设置代码,因此能生成更高效、更简短、更容易编写的代码。
其实 asyncore 应该被视为一个历史遗留物,根本不应该被使用。