我正在使用java.nio包在两个android设备之间创建TCP客户机-服务器连接。以下是客户端所做的工作:
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress(gameAddr, 8001));以下是服务器所做的工作:
try
{
tokenizer = new FixedSeparatorMessageTokenizer(Strings.DELIMITER, Charset.forName("UTF-8"));
selector = SelectorProvider.provider().openSelector();
sChan = ServerSocketChannel.open();
InetSocketAddress iaddr = new InetSocketAddress(InetAddress.getLocalHost(), 8001);
sChan.configureBlocking(false);
sChan.socket().bind(iaddr);
sChan.register(selector, SelectionKey.OP_ACCEPT);
sockets = new Vector<SocketChannel>();
}
catch (Exception e)
{
e.printStackTrace();
}
Iterator<SelectionKey> it;
try {
while (selector.isOpen())
{
selector.select();
it = selector.selectedKeys().iterator();
while (it.hasNext())
{
SelectionKey key = it.next();
it.remove();
if (!key.isValid())
{
continue;
}
if (key.isConnectable())
{
SocketChannel ssc = (SocketChannel) key.channel();
if (ssc.isConnectionPending()) ssc.finishConnect();
}
if (key.isAcceptable())
{
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel newClient = ssc.accept();
newClient.configureBlocking(false);
newClient.register(selector, SelectionKey.OP_READ);
sockets.add(newClient);
System.out.println("Connection from " + newClient.socket().getInetAddress().getHostAddress());
}
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer data = ByteBuffer.allocate(sc.socket().getSendBufferSize());
System.out.println("Data from " + sc.socket().getInetAddress().getHostAddress());
if (sc.read(data) == -1) //is this a socket close?
{
continue;
}
data.flip();
tokenizer.addBytes(data);
while(tokenizer.hasMessage())
{
ParsedMessage pm = new ParsedMessage(tokenizer.nextMessage());
pm.setAttachment(sc);
synchronized(Q) { Q.add(pm); }
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}它们都使用相同的端口8001 (我尝试了不同的端口),而且它们在同一个LAN中,因为UDP数据包实际上是从一个设备到另一个设备的。有什么问题吗?
发布于 2013-09-10 17:17:14
“连接拒绝”意味着来自客户端的连接尝试到达服务器(或服务器),但在指定的IP地址和端口上没有接受连接。由于您在这两种情况下都使用端口8001,最简单的解释是您的服务器或客户端没有使用正确的IP地址与另一端通信。
您正在使用这一行创建服务器套接字:
InetSocketAddress iaddr = new InetSocketAddress(InetAddress.getLocalHost(), 8001);最简单的解释是InetAddress.getLocalHost()没有返回与客户端使用的相同的IP地址。
https://stackoverflow.com/questions/18724231
复制相似问题