java.net.BindException: Address already in use: Cannot bind - java

I am sorry, I have searched but seem that all the answers dont fix my problem. I got this error when trying to create a ServerSocket to reply to multiple client message.
My server code:
package Server;
import java.net.*;
import java.io.*;
public class Server {
public final static int defaultPort = 7;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(defaultPort);
int i = 0;
while (true) {
try {
System.out.println("Server is running on port "
+ defaultPort);
Socket s = ss.accept();
System.out.println("Client " + i + " connected");
RequestProcessing rp = new RequestProcessing(s, i);
i++;
rp.start();
} catch (IOException e) {
System.out.println("Connection Error: " + e);
}
}
} catch (IOException e) {
System.err.println("Create Socket Error: " + e);
} finally {
}
}
}
class RequestProcessing extends Thread {
Socket channel;
int soHieuClient;
public RequestProcessing(Socket s, int i) {
channel = s;
clientNo = i;
}
public void run() {
try {
byte[] buffer = new byte[6000];
DatagramSocket ds = new DatagramSocket(7);
while (true) {
DatagramPacket incoming = new DatagramPacket(buffer,
buffer.length);
ds.receive(incoming);
String theString = new String(incoming.getData(), 0,
incoming.getLength());
System.out.println("Client " + clientNo
+ " sent: " + theString);
if ("quit".equals(theString)) {
System.out.println("Client " + clientNo
+ " disconnected");
ds.close();
break;
}
theString = theString.toUpperCase();
DatagramPacket outsending = new DatagramPacket(
theString.getBytes(), incoming.getLength(),
incoming.getAddress(), incoming.getPort());
System.out.println("Server reply to Client "
+ clientNo + ": " + theString);
ds.send(outsending);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
and my Client code:
package Client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
public class Client extends Object {
public final static int serverPort = 7;
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
InetAddress server = InetAddress.getByName("192.168.109.128");
Socket s = new Socket("192.168.109.128", 7);
String theString = "";
do {
System.out.print("Enter message: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
theString = br.readLine();
byte[] data = theString.getBytes();
DatagramPacket dp = new DatagramPacket(data, data.length,
server, serverPort);
ds.send(dp);
System.out.println("Sent to server server: " + theString);
byte[] buffer = new byte[6000];
DatagramPacket incoming = new DatagramPacket(buffer,
buffer.length);
ds.receive(incoming);
System.out.print("Server reply: ");
System.out.println(new String(incoming.getData(), 0, incoming
.getLength()));
} while (!"quit".equals(theString));
s.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
With the first Client connect, it works smoothly. But from the second Client, it throws java.net.BindException: Address already in use: Cannot bind.
Second Client can also send and receive message, but the Client No is still 0.
Server is running on port 7
Client 0 connected
Server is running on port 7
Client 0 sent: msg 0
Server reply to Client 0: MSG 0
Client 1 connected
Server is running on port 7
java.net.BindException: Address already in use: Cannot bind
Client 0 sent: msg 1 <<-- this one is sent from client 1 but Client No is 0
Server reply to Client 0: MSG 1

So, in RequestProcessing.run you decide to ignore the socket received at constructor and open a DatagramSocket on the same port as the one you are listening. What did you expect it will happen?
class RequestProcessing extends Thread {
Socket channel;
int soHieuClient;
public RequestProcessing(Socket s, int i) {
// *****************
// The processor should be using this socket to communicate
// with a connected client *using TCP Streams*
channel = s;
clientNo = i;
}
public void run() {
try {
byte[] buffer = new byte[6000];
// *****************************
// But, instead of using the this.channel, your code
// decides to ignore the TCP socket,
// then open another UDP *"server-side like"* socket.
// First time it's OK, but the second thread attempting
// to open another DatagramSocket on the same port will fail.
// It's like attempting to open two TCP ServerSockets on the
// same port
DatagramSocket ds = new DatagramSocket(7);
[Extra]
You will need to decide what protocol you'll be using: if you use a ServerSocket/Socket pair, then probably you want TCP communications, so no DatagramSockets.
If you want UDP communication, the ServerSocket/Socket has little to do with your approach and you'll need to use DatagramSocket. Construct it:
with a port on the serverside - and do it only once.
without any port for the client side then qualify each and every DatagramPackets with the server address and port.
See a tutorial on Oracle site on Datagram client/server configurations.

Everytime you receive a new client TCP connection on your main server socket, you spin up another instance of a RequestProcessing class. The first time you start the RequestProcessing instance thread, it successfully binds to UDP port 7. But then the second client connects and you try to spin up another instance of RequestProcessing while another one already exists. That's not going to work.
You should probably amend you protocol such that the RequestProcessing class picks a new port each time and signals back through to the TCP socket which port was chosen.
But if it was me, I would do this. Have a single RequestProcessing instance for all clients. Given that your UDP echo socket is just sending back a response to the address from which the packet arrived from, you only need one instance of this class.

A TCP solution:
An utility class (I'm too lazy to write the same code in multiple places):
public class SocketRW {
Socket socket;
BufferedReader in;
PrintWriter out;
public SocketRW(Socket socket)
throws IOException
{
super();
this.socket = socket;
if(null!=socket) {
this.in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out=new PrintWriter(socket.getOutputStream());
}
}
public String readLine()
throws IOException {
return this.in.readLine();
}
public void println(String str) {
this.out.println(str);
}
public Socket getSocket() {
return socket;
}
public BufferedReader getIn() {
return in;
}
public PrintWriter getOut() {
return out;
}
}
Server code - no more datagrams, just using Input/Output streams from the sockets, wrapped as Reader/Writer using the utility
public class TCPServer
implements Runnable // in case you want to run the server on a separate thread
{
ServerSocket listenOnThis;
public TCPServer(int port)
throws IOException {
this.listenOnThis=new ServerSocket(port);
}
#Override
public void run() {
int client=0;
while(true) {
try {
Socket clientConn=this.listenOnThis.accept();
RequestProcessing processor=new RequestProcessing(clientConn, client++);
processor.start();
} catch (IOException e) {
break;
}
}
}
static public void main(String args[]) {
// port to be provided as the first CLI option
TCPServer server=new TCPServer(Integer.valueOf(args[0]));
server.run(); // or spawn it on another thread
}
}
class RequestProcessing extends Thread {
Socket channel;
int clientNo;
public RequestProcessing(Socket s, int i) {
channel = s;
clientNo = i;
}
public void run() {
try {
SocketRW utility=new SocketRW(this.channel);
while (true) {
String theString=utility.readLine().trim();
System.out.println("Client " + clientNo
+ " sent: " + theString);
if ("quit".equals(theString)) {
System.out.println("Client " + clientNo
+ " disconnected");
this.channel.close();
break;
}
theString = theString.toUpperCase();
utility.println(theString);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
Client code - no more datagram sockets, using the same IO streams of the socket.
class TCPClient
implements Runnable // just in case you want to run multithreaded clients
{
Socket socket;
public TCPClient(InetAddress serverAddr, int port)
throws IOException {
this.socket=new Socket(serverAddr, port);
}
public void run() {
String theString="";
InputStreamReader isr = new InputStreamReader(System.in);
try {
SocketRW utility=new SocketRW(this.socket);
BufferedReader br = new BufferedReader(isr);
do {
System.out.print("Enter message: ");
theString = br.readLine().trim();
utility.println(theString);
System.out.println("Sent to server server: " + theString);
String received=utility.readLine();
System.out.println("Server reply: "+received);
} while (!"quit".equals(theString));
}
catch(IOException e) {
e.printStackTrace();
}
}
static public void main(String[] args) {
int port=Integer.valueOf(args[0]); // will throw if its no OK.
TCPClient client=new TCPClient(
InetAddress.getByName("192.168.109.128"),
port
);
client.run();
}
}

Related

Java Socket connected but can't sent message by OutputStream.write() but PrintStream will work

I'm an amateur in java socket programming. As I say in title, When I using PrintStream for socket output,it works;but it doesn't work if I using simply OutputStream.
I know the the client connected to the server cause' the server got the info of the client.So I think there must be something wrong with I/O stream, not the socket connection.
btw, I even use the flush() method for OutputStream.I think flush() will force to send all bytes, but it seems like it didn't work.
The Client Code:#line 12:
public class Clinet {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("==========Client============");
Socket socket = new Socket("localhost", 8888);// Server's addr and port
socket.setSoTimeout(3000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
String msgToSent = "Hello TCP";
outputStream.write(msgToSent.getBytes());
outputStream.flush();// FIXME:why flush() didn't work?why msg wasn't sent.
// read from socket input
String receivedMsg = new String(inputStream.readAllBytes());
System.out.println(receivedMsg);
socket.close();
}
}
When I using a filter stream like PrintStream,the msg can be sent to server.
The Server Code: if using PrintStream it will work perfectly with the Client:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket client = serverSocket.accept();
new Thread(new ServerHandler(client)).start();
}
}
}
class ServerHandler implements Runnable {
private Socket client;
ServerHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
InetAddress clientAddr = client.getInetAddress();
int clientPort = client.getPort();
System.out.println("client connected # " + clientAddr + ":" + clientPort);
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
while (true) {
String msg = new String(inputStream.readAllBytes());// FIXME: Why Server didn't receive Client's msg?
System.out.print("/" + clientAddr + "#" + clientPort + " : ");
System.out.println(msg);
String reply = "I received " + msg.length() + " words.";// return how many words the server got.
outputStream.write(reply.getBytes());
outputStream.flush();// flush to ensure send all msg,but seems doesn't work
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

How can I communicate between a server and a client using AWS when they are on different networks?

I am trying to establish a basic connection with my server from the client program. When I run my client/server on the same network, it works fine, but I don't know where to start when my client program is on my PC but my server program is on the EC2 instance.
I have set up an EC2 linux instance on AWS, and have loaded the server code onto it. The Client is on my PC.
To run the server, I'm using:
java GreetingServer 6000
To run the client, I'm using:
java GreetingClient <EC2 Public IP> 6000
I'm new to AWS and server-client communication, so if you know any good tutorials for this, that would be great!
Server Code:
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Code:
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Communicating through two separate computer using java sockets

I am trying to make a chat server and client that can communicate over two separate computers connected to the internet. One of them is connected to wifi and another one is through a modem. Here is my server code.
GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(100000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt("6066");
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient2
{
public static void main(String [] args)
{
String serverName = "10.2.3.100";
int port = Integer.parseInt("6066");
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
The IP address in Client code is of the computer where the server is running acquired by InetAddress.getLocalHost().getHostAddress(). When I run the server, it waits for the client. And when I run the client code from another computer, it doesn't connect. Is it possible to communicate like this through sockets in java ?
Yes, it is possible.
Your server has to have an external ip.
Also if your server is connected via WiFi, check router firewall settings.

Why is this socket null?

I am creating a multi client chat server and i am pretty confident that it will work (Correct me if i'm wrong), I have the issue that on the socket that the client connects to is null so the connections can't be created because i use if(Socket != null) so i don't get errors but i will explain my layout real fast. The server starts with a starter class called (LaunchServer) that uses the class object ClientConnector as Minecraft and then starts the method runServer(). Here is the code for this class:
public class LaunchServer
{
public static void main(String[] args)
{
System.out.println("[Info] Running");
ClientConnector Minecraft = new ClientConnector();
Minecraft.runServer();
}
}
It's fairly simple. This brings us to the ClientConnector class. Here we start at the method runServer(). Right away we have a try catch block. in that block we print a message that the server is trying to connect to the port 1337. we then create a new ServerSocket called serversocket. We then send a message to the console saying that we have bound to port and that we are awaiting a connection. While true, we create a new Socket socket that equals ServerSocket.accept(); OMG fuck it. Heres the code. you know what it does...
import java.util.ArrayList;
import java.net.*;
import java.io.*;
public class ClientConnector
{
public static ArrayList<Socket> Connections = new ArrayList<Socket>();
public static void runServer()
{
try
{
System.out.println("[Info] Attempting to bind to port 1337.");
#SuppressWarnings("resource")
ServerSocket serversocket = new ServerSocket(1337);
System.out.println("[Info] Bound to port 1337.");
System.out.println("[Info] Waiting for client connections...");
while(true)
{
Socket socket = serversocket.accept();
new ClientHandler(socket).start();
Connections.add(socket);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
This takes us to the handler class:
import java.io.*;
import java.net.*;
public class ClientHandler extends Thread
{
Socket Socket;
public ClientHandler(Socket socket)
{
socket = Socket;
System.out.println("[Info] Client connected on port 1337.");
}
public void run()
{
while(true)
{
for(int i = 0; i < ClientConnector.Connections.size(); i++)
{
try
{
if(Socket != null)//This stays null...
{
ObjectOutputStream Output = new //These can't be created...
ObjectOutputStream(Socket.getOutputStream());
ObjectInputStream Input = new ObjectInputStream(Socket.getInputStream());
whileChatting(Input, Output);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public static void sendMessage(String message, String returnedMessage, ObjectOutputStream out)
{
try
{
if(!message.isEmpty())
{
out.writeObject("\247c[Server]\247d " + message);
out.flush();
System.out.println("[Chat] Sent: " + message);
}
else
{
out.writeObject(returnedMessage);
System.out.println("[Chat] Sent: " + returnedMessage);
}
out.flush();
System.out.println("[Info] Fluching remaining data to stream.");
System.out.println("\n[Server] " + message);
}
catch(IOException ioException)
{
System.out.println("[Warning] Error: ioException # sendMessage line 76.");
}
}
public static void whileChatting(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
String message = "";
do
{
try
{
message = (String) input.readObject();
System.out.println("\n" + message);
sendMessage("", message, output);
}
catch(ClassNotFoundException classNotFoundException)
{
System.out.println("[Warning] Error: ClassNotFoundException # whileChatting line 1-7.");
System.out.println("\n idk wtf that user sent!");
}
}while(!message.equals("/stop"));
}
}
Read the run method. There you will see the null problem
Would the connection get accepted then passed to the hander class? How can a null connection get accepted? My question is how can i fix this problem?
The problem is you've got a logic error due to un-recommended naming conventions. You shouldn't name variables with keywords, like your Socket variable, and each variable should have a distinguishable name. e.g. not socket1, socket2 but serverSocket, clientSocket because that will make it easier for you and anyone else to read and fix your code.
Change
Socket Socket;
to
Socket connectedSocket;
and in your constructor
socket = Socket;
to
connectedSocket = socket;
then finally, in your run() method change
if(Socket != null)
to
if(connectedSocket != null)

Multithreaded Client Server Proxy java

I am currently implementing a multithreaded proxy server in java which will accept messages from clients and forward them to another server which will then acknowledge the reception of the message. However, i'm having trouble doing so. Could someone point out what i am doing wrong? Thanks.
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client{
public static void main(String[] args)
{
try
{
Socket client = new Socket(InetAddress.getLocalHost(), 6789);
if(client.isBound())
{
System.out.println("Successfully connected on port 6789");
}
Scanner scanner = new Scanner(System.in);
DataInputStream inFromProxy = new DataInputStream(client.getInputStream());
DataOutputStream outToProxy = new DataOutputStream(client.getOutputStream());
while(true)
{
String message;
System.out.print("Enter your message: ");
message = scanner.next();
outToProxy.writeUTF(message);
System.out.println(inFromProxy.readUTF());
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
System.exit(2);
}
}
}
The server code Server.java:
import java.io.*;
import java.net.*;
/**
* the client send a String to the server the server returns it in UPPERCASE thats all
*/
public class Server {
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(6780);
if(server.isBound())
{
System.out.println("Server successfully connected on port 6780");
}
Socket client = null;
while(true)
{
client = server.accept();
if(client.isConnected())
{
System.out.println("Proxy is connected");
}
DataInputStream inFromProxy = new DataInputStream(client.getInputStream());
DataOutputStream outToProxy = new DataOutputStream(client.getOutputStream());
System.out.println(inFromProxy.readUTF());
outToProxy.writeUTF("Message has been acknowledged!");
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
System.exit(2);
}
}
}
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class Proxy{
public static ServerSocket server = null;
public static Socket client = null;
public static void main(String[] args)
{
try
{
server = new ServerSocket(6789);
Socket clientsocket = null;
while(true)
{
client = server.accept();
if(client.isConnected())
{
System.out.println("Proxy is currently listening to client on port 6789");
}
clientsocket = new Socket(InetAddress.getLocalHost(), 6780);
Thread t1 = new ProxyHandler(client, clientsocket);
t1.start();
if(clientsocket.isBound())
{
System.out.println("Clientsocket successfully connected on port 6780");
}
Thread t2 = new ProxyHandler(clientsocket, client);
t2.start();
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
}
}
}
The Proxy code is:
import java.io.*;
import java.net.*;
public class ProxyHandler extends Thread {
private Socket socket;
private String message;
public ProxyHandler(Socket socket, Socket clientsocket)
{
this.socket = socket;
}
public void run()
{
message = "";
try
{
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while(true)
{
message = in.readUTF();
out.writeUTF(message);
System.out.println(message);
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
System.exit(2);
}
}
}
There is no multithreading here. There should be. Each accepted socket should be entirely processed in its own thread, in both the server and the proxy.
There is no point in testing isBound() immediately after creating and connecting a Socket. It will never be false.
There is no point in testing isConnected() immediately after an accept(). It will never be false.
The server must close each accepted socket once it is finished with it, i.e. once it has EOS from it (read() returns -1).
The proxy must also close each accepted socket once it is finished with it, ditto.
A proxy of any kind should just copy bytes. It shouldn't make assumptions about the format of the data. Don't use readUTF(), use count = read(byte[]) and write(buffer, 0, count). That also means that you don't need DataInput/OutputStreams in the proxy.

Categories

Resources