Java 7 doesn't throw BindException when binding an already used port using ServerSocket - sockets

I'm experimenting on ServerSocket in Java on Windows 7 x64.
I wrote a little program that host a HTTP server on port 8080 and only returns a static HTML response that contains the toString() of the class loader.
What I did in the program mainly:
Create a ServerSocket
call setReuseAddress(false) on the serverSocket
Bind port 8080 to this socket
Use a forever loop to accept socket and give response
First I tried with JRE 1.6.0_23 and everything is great: first instance launched and responds normally, second instance cannot be launched since exception is thrown:
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
Unexpected thing happens when I tried with JRE 1.7.0_5: both instance can be launched successfully but only the first instance gives responses. After the first instance is kill, the second instance then starts to responds.
Am I doing anything wrong or is this a bug of JRE 7?
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServerSocket {
private static final String HEADER = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n"
+ "Connection: close\r\n" + "\r\n";
private static final int PORT = 8080;
private static void handle(Socket socket) {
System.out.println(socket.getInetAddress() + ":" + socket.getPort());
StringBuilder buffer = new StringBuilder();
buffer.append(HEADER);
buffer.append(TestServerSocket.class.getClassLoader());
try {
socket.getOutputStream().write(buffer.toString().getBytes());
} catch (IOException e) {
} finally {
try {
socket.close();
} catch (IOException e) {
}
}
}
public static void main(String[] args) throws IOException {
int port;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
port = PORT;
}
final ServerSocket server = new ServerSocket();
server.setReuseAddress(false);
server.bind(new InetSocketAddress(port));
// Terminator thread, stop when Ctrl-D is entered
new Thread() {
public void run() {
try {
while (System.in.read() != 4);
} catch (IOException e) {
e.printStackTrace();
}
try {
server.close();
} catch (IOException e) {
}
System.exit(0);
}
}.start();
System.out.println("Listening on: " + port);
Socket client = null;
while (true) {
try {
client = server.accept();
handle(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

To Isolate the problem, I would recommend that you run the following test code.
Apache HttpCore basic server. It's standard API and uses ServerSocket in this particular example, so there is a very small chance that it would fail on your environment ( java 7).
In case it fails you will know for sure problem is not with your code. Meanwhile I will try your code on JDK 7 on my work-machine and will update.

Related

Netty connection pool not sending messages to server

I have a simple netty connection pool and a simple HTTP endpoint to use that pool to send TCP messages to ServerSocket. The relevant code looks like this, the client (NettyConnectionPoolClientApplication) is:
#SpringBootApplication
#RestController
public class NettyConnectionPoolClientApplication {
private SimpleChannelPool simpleChannelPool;
public static void main(String[] args) {
SpringApplication.run(NettyConnectionPoolClientApplication.class, args);
}
#PostConstruct
public void setup() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.remoteAddress(new InetSocketAddress("localhost", 9000));
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new DummyClientHandler());
}
});
simpleChannelPool = new SimpleChannelPool(bootstrap, new DummyChannelPoolHandler());
}
#RequestMapping("/test/{msg}")
public void test(#PathVariable String msg) throws Exception {
Future<Channel> future = simpleChannelPool.acquire();
future.addListener((FutureListener<Channel>) f -> {
if (f.isSuccess()) {
System.out.println("Connected");
Channel ch = f.getNow();
ch.writeAndFlush(msg + System.lineSeparator());
// Release back to pool
simpleChannelPool.release(ch);
} else {
System.out.println("not successful");
}
});
}
}
and the Server (ServerSocketRunner)
public class ServerSocketRunner {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
System.out.println("New client connected");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));) {
String inputLine, outputLine;
out.println("Hello client!");
do {
inputLine = in.readLine();
System.out.println("Received: " + inputLine);
} while (!"bye".equals(inputLine));
System.out.println("Closing connection...");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
DummyChannelPoolHandler and DummyClientHandler just print out events that happen, so they are not relevant. When the server and the client are started and I send a test message to test endpoint, I can see the server prints "New client connected" but the message sent by client is not printed. None of the consecutive messages sent by client are printed by the server.
If I try telnet, everything works fine, the server prints out messages. Also it works fine with regular netty client with same bootstrap config and without connection pool (SimpleNettyClientApplication).
Can anyone see what is wrong with my connection pool, I'm out of ideas
Netty versioin: 4.1.39.Final
All the code is available here.
UPDATE
Following Norman Maurer advice. I added
ChannelFuture channelFuture = ch
.writeAndFlush(msg + System.lineSeparator());
channelFuture.addListener(writeFuture -> {
System.out
.println("isSuccess(): " + channelFuture.isSuccess() + " : " + channelFuture.cause());
});
This prints out
isSuccess: false : java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion)
To fix it, I just converted String into ByteBuf
ch.writeAndFlush(Unpooled.wrappedBuffer((msg + System.lineSeparator()).getBytes()));
You should check what the status of the ChannelFuture is that is returned by writeAndFlush(...). I suspect it is failed.

Socket implementation with ObjectInputStream - can't read object

For a Java class I am taking, I need to use sockets to pass data back and forth between client and server. While I can get examples to work passing string data, I need to be able to pass custom class objects (i.e. a product) and lists of these objects back and forth. I cannot get the server piece to successfully read the input. I tried to create a simple example of my code to see if anyone can pinpoint the issue. I do understand that I don't have the code complete, but I cannot even get the server to read the object the the class is writing to the stream (in this case, I am writing a string just in an attempt to get it to work, but need to read/write objects). Here is my code. I have spent hours and hours trying this and researching other people's questions and answere, but still can't get this to work.
Here the sample code:
simple server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class simpleServer {
public static final int PORT_NO = 8888;
static ObjectInputStream serverReader = null;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket = new ServerSocket(PORT_NO);
System.out.println("... server is accepting request");
Object myObject = null;
while (true) {
Socket socket = serverSocket.accept();
System.out.println("creating reader");
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
serverReader = new ObjectInputStream(socket.getInputStream());
System.out.println("created reader");
try {
System.out.println("try to read");
myObject = serverReader.readObject();
System.out.println("read it");
System.out.println(myObject);
if (myObject != null) objOut.writeUTF("Got something");
else objOut.writeUTF("got nothing");
if ("quit".equals(myObject.toString())) serverSocket.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("cath for readobject");
}
catch (Exception e) {
System.out.println("other error");
System.out.println(e.getMessage());
}
}
}
}
simple client:
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket("localhost", ProductDBServer.PORT_NO);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeUTF("loadProductsFromDisk");
objOut.flush();
String myString = objIn.toString();
//System.out.println(myString);
if (!"quit".equals(objIn.toString().trim())) {
//System.out.println("reading line 1");
String line;
try {
line = (String)objIn.readObject();
//System.out.println("line is " + line);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
objIn.close();
//System.out.println("result: " + line);
}
System.out.println("closing socket");
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Unknownhostexception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("ioexception");
e.printStackTrace();
}
}
The code appears to run to the point on the server side where it trys to read the object I sent, and then dies. Can someone see what I am doing wrong? This seems to be such a simple thing to do, and yet I can't seem to get it to work. Thanks for any help!
To write objects to an ObjectOutputStream you need to call writeObject().
Not writeUTF().
To read objects from an ObjectInputStream you need to call readObject().
Not toString().
See in your code:
// Simple Client
objOut.writeUTF("loadProductsFromDisk"); // Line 8
You are sending the String "loadProductsFromDisk" in the UTF-8 format towards the server side.
So in order to receive it and read it over the server side, you will need something like this:
String clientReq = serverReader.readUTF();
Where, serverReader is your ObjectInputStream object.
Otherwise, if you wish to send and receive objects you must use the
writeObject() & readObject() methods respectively.

javax.microedition.io.ConnectionNotFoundException: error 10061 in socket::open

javax.microedition.io.ConnectionNotFoundException: error 10061 in socket::open
I have this error with j2me - in execution.
I tried searching, but it didn't help.
Code:
Connector.open("socket://127.0.0.1:7777")
According to ConnectionNotFoundException documentation "This class is used to signal that a connection target cannot be found, or the protocol type is not supported".
socket is a supported protocol, so the connection target cannot be found. Be sure that 127.0.0.1:7777 is up, running and that is does support receiving a Socket connection.
You may try below Java code:
public class Server {
static boolean done = false;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(7777);
while (!done) {
final Socket socket = server.accept();
new Thread() {
public void run() {
treatSocket(socket);
}
}.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void treatSocket(Socket socket) {
// treat socket data
}
}

How can I test, whether my deployed background server application on AWS beanstalk gets messages through a socketstream with an android mobile client?

The overall topic is actually like a Chat Application sending a simple string message to an aws server, which uses the message to make calculations server-side and sending a simple string message as a solution back to the client.
Server: I have written a Server Class and deployed it through eclipse to aws beanstalk. (see code Server)
Client: My android device creates a socket, establishes a successful connection to my aws beanstalk ip and 8080 port, while iterating through an endless while loop in a thread listening to incoming messages from the server. (see code Client and ClientThread)
Problem: My problem is that I don't know how to check whether the server receives the connection request and messages from the client. How do I make sure, that code on aws beanstalk actually runs in background continuously listening for incoming connections? I have deployed the code, does aws beanstalk automatically start the main method of the Server Class and runs it infinitely?
Here's the server code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
ServerSocket server = null;
System.out.println("Trying to open serversocket!");
try {
server = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error on port: 8080 " + ", " + e);
System.exit(1);
}
System.out
.println("Server setup and waiting for client connection ...");
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.out.println("Did not accept connection: " + e);
System.exit(1);
}
System.out
.println("Client connection accepted. Moving to local port ...");
try {
DataInputStream streamIn = new DataInputStream(
new BufferedInputStream(client.getInputStream()));
DataOutputStream streamOut = new DataOutputStream(
new BufferedOutputStream(client.getOutputStream()));
boolean done = false;
String line;
int i = 4;
while (!done) {
line = streamIn.readUTF();
if (line.equalsIgnoreCase(".bye"))
done = true;
else
System.out.println("Client says: " + line);
if (i == 4) {
streamOut
.writeUTF("Actually connected to Server with round "
+ i);
streamOut.flush();
i++;
}
}
streamIn.close();
streamOut.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}
}
Here's the client code:
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
class Client implements Runnable {
private Socket socket = null;
private InputStream streamIn = null;
private OutputStream streamOut = null;
public InputStream getStreamIn() {
return streamIn;
}
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
Log.d("DEBUG", "Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
Log.d("DEBUG", "Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
Log.d("DEBUG", "Unexpected exception: " + ioe.getMessage());
}
}
public void start() throws IOException {
streamIn = socket.getInputStream();
streamOut = socket.getOutputStream();
}
public void run() {
try {
streamOut.write(streamIn.read());
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
stop();
}
}
public void handle(String msg) {
if (msg.equals(".bye")) {
System.out.println("Good bye. Press RETURN to exit ...");
stop();
} else
System.out.println(msg);
}
public void stop() {
try {
if (streamIn != null)
streamIn.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public void send(String msg) {
PrintWriter printwriter = new PrintWriter(streamOut);
printwriter.write(msg);
printwriter.flush();
}
}
Here's the ClientThread Code
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import android.os.Handler;
public class ClientThread extends Thread {
private Client client;
private InputStream input;
private String output;
private Handler handler;
private Runnable runner;
public ClientThread() {
}
public ClientThread(Client client, Handler handler, Runnable runner) {
this.setClient(client);
this.input = client.getStreamIn();
this.handler = handler;
this.runner = runner;
this.output = "";
}
public void run() {
int status = 0;
while (status != -1) {
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (status != '~'){
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
output = output + String.valueOf((char) status);
handler.post(runner);
}
output = output + "\n";
}
}
public String giveString(){
return output;
}
public void setClient(Client client) {
this.client = client;
}
public Client getClient() {
return client;
}
}
Thank you for your time!

Java socket programming problem

Hey,
I am trying to run this socket programming code.
This is the code on the server side -
package sockettest;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(139);
}
catch (IOException e)
{
System.err.println("not able to listen on port");
System.exit(1);
}
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // Out is Outputstream is used to write to the Client .
BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); // in is used to read the Client's input.
String inputLine, outputLine;
out.println("Hey! . Who are you?"); // Writes to client as "Hey! . Who are you?"
while ((inputLine = in.readLine()) != null)
{
// Reads the input from the Client. if it is "bye" the program ends.
if (inputLine.equalsIgnoreCase("Bye"))
{
out.println("Bye");
break;
}
else
{
out.println("Hello Mr. " + inputLine);
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
This is the code running on the client side -
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
kkSocket = new Socket("192.168.2.3", 139);
out = new PrintWriter(kkSocket.getOutputStream(), true); // Out may be used to write to server from the client
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); // in will be used to read the lines sent by the Server.
}
catch (UnknownHostException e)
{
System.err.println("Unidentified host.");
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromClient;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye"))
break;
fromClient = stdIn.readLine();
if (fromClient != null) {
System.out.println("Client: " + fromClient);
out.println(fromClient);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
I'm running the codes on eclipse in both the client and the server side. Using netstat -an command in cmd prompt, i can see that a connection has been established between the client and the server but i cannot communicate and eclipse is not showing any output too. What seems to be wrong??
You haven't told us what the problem is. However, from a cursory glance at your code, I would advise against listening on port 139 as this is already used by NetBios under Windows and may cause a conflict.
also your Server code is missing
the initialization of inputLine,
e.g
String inputline = "";
before the while loop
keep in mind that Socket's are blocked if you read or write...
your client is reading all the time because it waits for every information on the server
until it is null
and your server also reads all the time and is waiting for any input..
so as long as server and client are waiting for input, no one will receive any data.
try to think of a protocol to communicate between the server and the client.
e.g
Sever to Client: Hello Who are you?
Client receives Data and replies: Client
Server receives Information: You Are now authorized, what ya gonna do?
and so on ^^
also out.flush() is needed to send a message