while (true) {
ServerSocket myServerSocket = new ServerSocket(9999);
Socket skt = myServerSocket.accept();
Handling obj = new Handling();
obj.handle(skt);
}
When i first try this it works fine and accepts the Socket but then when it loops back it says the address is in use. How do I fix this?
Don't create a new ServerSocket in the loop - you only need to accept in the loop:
ServerSocket myServerSocket = new ServerSocket(9999);
while (true) {
Socket skt = myServerSocket.accept();
Handling obj = new Handling();
obj.handle(skt);
}
Related
I'm trying to create a server in Java using Sockets. I create a ServerSocket using ServerSocket serverSocket = new ServerSocket(port); and then attempt to connect using Socket clientSocket = serverSocket.accept();. I send the request through Postman.
My issue is that whenever I send a request, I get the output:
New client connected
input: null
closed!
New client connected
input: PUT / HTTP/1.1
closed!
I'm confused as to why the client connects twice, and why the first request is always empty.
Full code:
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
BufferedReader br = new BufferedReader(new InputStreamReader((clientSocket.getInputStream())));
String input = br.readLine();
System.out.println("input: " + input);
clientSocket.close();
System.out.println("closed!");
}
I'm using this code to constantly accept when a new Socket connect to Server:
while (true) {
Socket socket = null;
socket = ss.accept();
System.out.println("A client is connect...\n");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Thread acceptClient = new Thread(new ClientHandler(socket, in, out));
acceptClient.start();
}
But when a connection is created, I see this in the console:
A client is connect...
A client is connect...
A client is
connect...
I don't understand why this line is displayed 3 times. Can anyone explane?
I am trying to figure out how to make this piece of code into TCP instead of UDP
DatagramPacket answerDP = null;
answerDP = new DatagramPacket(new byte[110], 110);
What do I use in TCP instead of DatagramPacket?
The same goes for DatagramSocket, what do I use in TCP instead?
DatagramSocket socket = null;
socket = new DatagramSocket();
socket.send(packet);
socket.setSoTimeout(5000); //wait for answar max. 1 sec.
socket.receive(answerDP);
DatagramSocket in TCP is basically ServerSocket
So for example, to initialise it:
ServerSocket welcomeSocket = new ServerSocket(6789);
And the client socket would be something like:
Socket clientSocket = new Socket("localhost", 6789);
Set timeout works the same
socket.setSoTimeout(5000);
See a simple example here
I want to send an object(array) from a client to a server. I use the ObjectInputStream and the ObjectOutputStream. However, this invokes an error, that these methods are not defined in serverSocket class.
How do I resolve the situation ??`
public int[] readResponse() throws IOException, ClassNotFoundException{
int[] x = new int[5];
ObjectOutputStream cO = new ObjectOutputStream(serverSocket.getOutputStream()); //here is the error
ObjectInputStream cI = new ObjectInputStream(serverSocket.getInputStream()); // here is the error
cO.writeObject(x);
x = (int[]) cI.readObject();
for (int i = 0; i < 5; i++){
System.out.println(x[i]);
}
return x;
}
A java.net.ServerSocket is not meant to be used for actual input and output; it is a socket for listening on the server to incoming connection requests which are accepted, resulting in a java.net.Socket which is then the one for reading and writing.
Socket socket = serverSocket.accept();
ObjectInputStream cI =
new ObjectInputStream(socket.getInputStream());
On the client side, a java.net.Socket is created by calling the constructor and connected, via an address, to the client.
Socket socket = new Socket( address, port );
ObjectOutputStream cO =
new ObjectOutputStream(socket.getOutputStream());
I have an interesting question. I am trying to establish a peer to peer connection which means a client process acts both as a server and client. Ideally, it should have a client socket (Socket class) and a server socket(Server Socket class). Now I tried to use this concept but it does not work. Please take a look at it:
public static void main(String argv[]) throws Exception
{
Socket clientSocket = null;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Enter the server port u want to be assigned to this peer:");
sentence = inFromUser.readLine();
System.out.println("writing current port to client = "+ sentence);
outToServer.writeBytes("p~"+sentence + "\n" );
int serverport = Integer.parseInt(sentence);
ServerSocket server = new ServerSocket(serverport);
Socket client;
//client
System.out.println("enter port no of the server port of an other peer:");
int msg=Integer.parseInt(inFromUser.readLine());
clientSocket = new Socket("localhost", msg);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("hi");
while(true)
{
//server port listens infinitely and spawns new thread
System.out.println("inside true");
client = server.accept();
Thread serverThread = new Thread(new acceptconnection1(client));
serverThread.start();
}}}
class acceptconnection1 implements Runnable {
BufferedReader inFromClient, inn;
DataOutputStream ds;
Socket socket;
int peersocket;
String clientSentence;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (Socket socket,) throws IOException{
this.socket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(socket.getInputStream()));
ds = new DataOutputStream(socket.getOutputStream());
}
#Override
public void run () {
String cs,a;
try {
System.out.println("waiting for connection ");
if(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("Message from other peer" + clientSentence);
}
} catch (IOException ex) {
Logger.getLogger(acceptconnection1.class.getName()).log(Level.SEVERE, null, ex);
}}}
Output:
when I create two client processes,
o/p of client1:
Enter the server port u want to be assigned to this peer:
1111
writing current port to client = 1111
hi enter port no u want to connect to:
2222
inside true
inside true
waiting for connection
Enter the server port u want to be assigned to this peer:
2222
writing current port to client = 2222
hi enter port no u want to connect to:
1111
inside true
inside true
waiting for connection
what happens is both of them wait for connections. how do i solve this?
You have a deadlock condition. To result this, create the ServerSocket first so the Socket has something to talk to. Create the Socket which will connect but do nothing until accepted. Then accept connections.
BTW: You don't need to create two connections for traffic to pass both ways. Once a connection has been established, you can use that one connection as client-server, or server-server or what ever.