Java - cannot connect to server - connection refused - java

I am using the java.nio package to create a TCP client-server connection between two android devices.
Here is what the client does:
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress(gameAddr, 8001));
Here is what the server does:
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();
}
}
They both are using the same port 8001 (I tried different ports) and they are in the same LAN because UDP packets actually make it from one device to the other. What can be the problem?

"Connection refused" means that the connection attempt from the client reached the server (or a server), but there was nothing accepting connections at the specified IP address and port. Since you are using port 8001 in both cases, the simplest explanation is that either your server or your client aren't using the correct IP address to communicate with the other end.
You're using this line to create the server socket:
InetSocketAddress iaddr = new InetSocketAddress(InetAddress.getLocalHost(), 8001);
the simplest explanation is that InetAddress.getLocalHost() isn't returning the same IP address that the client is using.

Related

Why a key has to be removed from selectedKeys

This is a simple server, I used nc as clients to connect to the server, the first client went through and entered the acceptHandler. However, the second client cannot trigger the select to return a number greater than 0 (the return value of select is 0). I see that removing the processed key will resolve the issue, what I don't understand is that why a new connection cannot trigger an event when the serverSocket is still registered with the selector
static ServerSocketChannel server;
static Selector selector;
public static void main(String[] args) throws IOException {
server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(9090));
server.configureBlocking(false);
selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int num;
while ((num = selector.select()) > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectionKeys.iterator();
while (iter.hasNext()) {
SelectionKey sk = iter.next();
// iter.remove();
if (sk.isAcceptable()) {
acceptHandler(sk);
} else if (sk.isReadable()) {
readHandler(sk);
}
}
}
}
}
public static void acceptHandler(SelectionKey sk) {
System.out.println("accept handle");
ServerSocketChannel server = (ServerSocketChannel) sk.channel();
SocketChannel client = null;
try {
client = server.accept(); // return null if no pending connections
if (client != null) {
client.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(65535);
client.register(selector, SelectionKey.OP_READ, buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}

How can I handle multipart form data in Java NIO Htttp Server

I have implemented a Non Blocking Htttp Server by using Java NIO. It works fine for x-www-form-urlencoded POST requests. But when i try it for a HTTP multipart request with large file, it is not working. In that situation Server unable to make response to http client. This is my source code for the NIO Server.
public class TCPServer {
public static void main(String[] args) {
TCPServer server = new TCPServer();
server.listen();
}
public void listen() {
try {
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel
.open();
InetSocketAddress serverAddress = new InetSocketAddress(8080);
serverSocketChannel.bind(serverAddress);
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector,
SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel clientSocketChannel = null;
try {
clientSocketChannel = (SocketChannel) key.channel();
ByteBuffer clientBuffer = ByteBuffer.allocate(1024);
StringBuilder requestStringBuilder = new StringBuilder();
int bytesRead = clientSocketChannel
.read(clientBuffer);
while (bytesRead > 0) {
clientBuffer.flip();
String result = new String(clientBuffer.array());
requestStringBuilder.append(result);
clientBuffer.compact();
bytesRead = clientSocketChannel.read(clientBuffer);
}
System.out.println("request-----");
System.out
.println(requestStringBuilder.toString());
clientSocketChannel.write(ByteBuffer
.wrap("reply from server".getBytes()));
clientSocketChannel.register(selector,
SelectionKey.OP_WRITE);
} catch (Exception e) {
System.err.println(e.getMessage());
clientSocketChannel.close();
}
} else if (key.isWritable()) {
SocketChannel clientSocketChannel = null;
try {
clientSocketChannel = (SocketChannel) key.channel();
clientSocketChannel.close();
} catch (Exception e) {
System.err.println(e.getMessage());
clientSocketChannel.close();
}
}
iterator.remove();
}
}
}catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Is there any other way to handle HTTP multipart request inside Java NIO non blocking server.How can i fix this. Thanks.
This is similar to another question: Servlet 3.1 - Multipart async processing, but I'll answer here as the solution works with plain non-blocking IO too.
Synchronoss Technologies recently open sourced a non-blocking HTTP multipart parser here.
As your non-blocking server receives data, you just need to pass the incoming bytes to the NioMultipartParser. The parser will make callbacks to your code for each of the parts received.
Disclaimer: I work for Synchronoss Technologies. We wrote this for Servlet 3.1 but it should intentionally work in regular non-blocking applications too, so hopefully others will find this library useful.

Nonblocking Echo Server - Java

This is an Echo Server. I cannot understand why after first connection with client, even after client close the connection still the server is printing "Reading.." and "Writing..". Shouldn't the server block with select() method?
Thanks
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.io.IOException;
public class EchoServer
{
public static int DEFAULT_PORT=7;
public static void main(String [] args)
{
ServerSocketChannel serverChannel;
Selector selector;
try
{
serverChannel = ServerSocketChannel.open();
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = new InetSocketAddress(DEFAULT_PORT);
ss.bind(address);
serverChannel.configureBlocking(false);
selector=Selector.open();
serverChannel.register(selector,SelectionKey.OP_ACCEPT);
} catch(IOException ex) {ex.printStackTrace(); return;}
while(true)
{
int selectednum=0;
try{
selectednum=selector.select(); //blocks
}catch (IOException ex) {ex.printStackTrace(); break;}
if (selectednum>0) {
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 from "+client);
client.configureBlocking(false);
SelectionKey clientKey=client.register(
selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
ByteBuffer buffer = ByteBuffer.allocate(100);
clientKey.attach(buffer);
}
if (key.isReadable()){
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
System.out.println("Reading..");
client.read(output);
}
if (key.isWritable()){
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
output.flip();
System.out.println("Writing..");
client.write(output);
output.compact();
}
} catch (IOException ex) {
key.cancel();
try { key.channel().close();}
catch (IOException cex) {};
}
}
}
}
}
}
You aren't detecting end of stream when reading from the client. The read() method returns -1. When that happens you should close the channel.

How to do Java serialization with ObjectInputStream when using NIO Selector?

How can you read an object directly from a SocketChannel that is non-blocking? It's being accessed with a Selector. The following code is broken (it throws an IllegalBlockingModeException) and I don't know how to fix it, except for perhaps using ByteBuffer, which I'd rather not (for now, at least):
public static void main(String[] args) {
try {
Selector selector = Selector.open();
ServerSocketChannel listener = ServerSocketChannel.open();
listener.socket().bind(new InetSocketAddress(50001));
listener.configureBlocking(false);
listener.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Iterator<SelectionKey> i = selector.selectedKeys().iterator();
while (i.hasNext()) {
SelectionKey key = i.next();
i.remove();
if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
ObjectInputStream ois = new ObjectInputStream(channel.socket().getInputStream());
String message = (String) ois.readObject();
System.out.println("Server received message: " + message);
}
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}

How to write data to Socket opened by Flex from Java Server

Ok, basically my Flex app will open up a socket and listen on it. My java program will write some string to this port.
My AS3 code is
private function onRecvClick():void
{
var host:String = "localhost";
var port:int = 9090;
var socket:Socket = new Socket(host, port);
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(DataEvent.DATA, onData);
socket.connect(host, port);
}
And my Java code is :
private ClientSocket()
{
try
{
String host = "localhost";
int port = 9090;
Socket socket = openSocket(host, port);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("HelloTest");
writer.flush();
}
catch (Exception e)
{
System.out.println(e);
}
}
private Socket openSocket(String server, int port) throws Exception
{
Socket socket;
// create a socket with a timeout
try
{
InetAddress inteAddress = InetAddress.getByName(server);
SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);
// create a socket
socket = new Socket();
// this method will block no more than timeout ms.
int timeoutInMs = 10*1000; // 10 seconds
socket.connect(socketAddress, timeoutInMs);
return socket;
}
catch (SocketTimeoutException ste)
{
System.err.println("Timed out waiting for the socket.");
ste.printStackTrace();
throw ste;
}
}
While trying to write to the socket, i am getting this java.net.ConnectException: Connection refused: connect. Funny thing is that the socket in Flex doesn't seem to dispatch any events, is it normal for that to happen?
Unless I'm misreading the docs completely, both flash.net.Socket and java.net.Socket are client sockets.
You need one side to be a server socket to be able to connect them together.
For the server side in Java, look at this walkthrough: Socket Communications.

Categories