So I have my server that looks like this
import java.net.*;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
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 = 5000;
try {
Thread t = new Server(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}
}
}
And when I run it, everything goes fine. I also have my client which looks like this.
import java.net.*;
import java.io.*;
public class Client {
public static void main(String [] args) {
String serverName = "Server";
int port = 5000;
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) {
System.out.println("Error!");
}
}
}
After running my client I get this in the console.
Connecting to Server on port 5000
java.net.UnknownHostException: Server
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at maple.Client.main(Client.java:16)
Line 16 looks like this
Socket client = new Socket(serverName, port);
EDIT:
After changing to a valid server address when I run the code I only get certain statements to run and then it just times out. Why is this?
Waiting for client on port 5000...
Just connected to /127.0.0.1:57355
Hello from /127.0.0.1:57355
Waiting for client on port 5000...
Socket timed out!
The server name is assigned to the String literal "Server" rather than a valid host address.
Its timing out because in constructor you are setting a 20 sec time to live.
serverSocket.setSoTimeout(20000);
Remove this and you should be fine.
Related
Hello stackoverflow community,
i am stuck at a problem regarding socket communication in Java.
Here is the sample code of my Server and Client class:
Server:
public class OTPServer {
static ServerSocket serverSocket;
final static int PORT = 4242;
static Socket clientConnection;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Socket initialized");
String serverMessage = "Hello, I am the Host";
ServerTool serverTool = new ServerTool();
while (true) {
clientConnection = serverSocket.accept();
if(clientConnection.isConnected()) {
System.out.println("Client connected");
}
BufferedReader clientInputReader = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
DataOutputStream serverOutput = new DataOutputStream(clientConnection.getOutputStream());
System.out.println("Sending message to client: " + serverMessage);
serverOutput.writeBytes(serverTool.encodeMessage(serverMessage));
serverOutput.flush();
String clientMessage = clientInputReader.readLine();
System.out.println("Encoded answer from client: " + clientMessage);
String decodedMessage = serverTool.decodeMessage(clientMessage);
System.out.println("Decoded answer from client: " + decodedMessage);
serverOutput.close();
clientInputReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Hello, I am the OTP Server!");
}
Here is the Client:
public class OTPClient {
static Socket clientSocket;
final static int PORT = 4242;
final static String HOST = "localhost";
public static void main(String[] args) {
System.out.println("I am the OTP Client!");
String serverMessage;
String clientResponse = "I am the Client";
OTPTool otpTool = new OTPTool();
try {
clientSocket = new Socket(HOST, PORT);
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Connection to Host established");
serverMessage = serverInput.readLine();
System.out.println("Encoded Message from Server: " + serverMessage);
String decodedMessage = otpTool.decodeMessage(serverMessage);
System.out.println("Decoded message from Server: " + decodedMessage);
System.out.println("Answering with own message: " + clientResponse);
outputStream.writeBytes(clientResponse);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Now where is my problem:
The connection establishes and the Server seems to send its message to the client and waits for a answer. The Client does not print the message he got from the Server.
As soon as i cancel the Server the client prints the message it gets from the server as well as the information, that the answer is send end exits with exit code 0 so it seems that this part is fine it just is stuck somehow.
I already tried to flush the outputStream as you see in the example code given.
Is there something obvious im missing?
I know, this is really basic stuff but its my first time using sockets for communication.
Thank you in advance!
Best Regards,
Ronny
Btw: i know that the server only connects to one client requesting a connection. Thats absolutely sufficient for my use.
It is getting stuck because serverInput.readLine(); blocks until either a line break or end of file is encountered. On the server side, you are not sending a line break, so the client blocks.
Found some similar questions but no answer, so here goes -
Attached code is self contained, compilable and runnable to set up a server on my computer. Socket gets created, and I can do a telnet <ip_address> 9162 or telnet localhost 9162 from my local machine. From a remote host, telnet does not get connected. Any ideas? TIA.
import java.io.*;
import java.net.*;
public class TestServerSocket {
public static void main(String args[]) throws IOException {
final int portNumber = 9162;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while (true) {
pw.print("What's you name? ");
pw.flush();
String str = br.readLine();
if (str.trim().length() == 0)
break;
pw.println("Hello, " + str);
}
pw.close();
socket.close();
}
}
}
I have a socket programming code that goes..
Server Program
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(50000);
}
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)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
And the client side code that is...
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, 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)
{
}
}
}
The code compiles fine. But when i run the program, first the server and then the client, the server displays that
Waiting for client on port 9000...
Socket timed out!
and the client shows
Connecting to MyServerName on port 9000
What is wrong with the code?? I have tried increasing and decreasing the timeout values but it gives the same output.
What is wrong with the code?
There's nothing wrong with your code. You set a 50 second accept timeout, accept blocked for 50 seconds without a client trying to connect, so a SocketTimeoutException was thrown. Everything here is working as designed.
Of course it's possible that:
your accept timeout is too short
you don't want to abort your server just because of an accept timeout
you don't want an accept timeout at all.
All of these are design decisions that depend on your requirements.
It's also possible that you got the host name wrong in the client, but as you're ignoring exceptions in the client:
catch(IOException e)
{
}
there is no way you will ever find out. Never ignore IOExceptions.
Above code is perfectly working with sName in client as 'localhost', since I am running both client and server in my local:
String sName = "localhost";
Verify your server-name if you are expecting client to connect to server.
My TCP Server
public static void main(String argv[]) throws Exception {
ServerSocket server = new ServerSocket(3333);
System.out.println("Server started");
while (true) {
Socket socket = server.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Received: " + input.readLine() + "\n");
}
}
My TCP Client.
public static void main(String[] args) throws IOException {
for (int i = 1; i < 50000; i++) {
Socket clientSocket = new Socket("localhost", 3333);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(i + "\n");
clientSocket.close();
System.out.println(i);
}
}
The loop in TCP client runs till 16374 and stopped, throwing this exception.
...
...
...
16372
16373
16374
Exception in thread "main" java.net.SocketException: No buffer space available (maximum connections reached?): connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at mawia.test.Client.main(Test.java:11)
What is wrong with my code?
Why do I get this error?
How to solve this problem?
Fildor is right, you are creating too many connections or Socket handles, this internally translates to allowed open-file-handles per process which in most probability you are breaking.
Ideal approach would be for client to keep on sending data (50000 records) on one connections i.e. Socket and Server should handle processing this data in a separate thread (So you can run multiple TCP Client concurrently):
TCP Server
public static void main(String argv[]) throws Exception {
ServerSocket server = new ServerSocket(3333);
System.out.println("Server started");
while (true) {
final Socket socket = server.accept();
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("Server received message from client: ");
BufferedReader input;
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(!socket.isClosed() && socket.getInputStream().available() > 0){
System.out.println("Received: " + input.readLine() + "\n");
}
System.out.println("Client disconnected from server");
} catch (IOException e) {
//break;
}
}
});
t.start();
}
}
TCP Client
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket("localhost", 3333);
for (int i = 1; i < 50000; i++) {
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(i + "\n");
outToServer.flush();
System.out.println(i);
}
clientSocket.close();
}
Also try once with adding flush() in your TCP Client code before closing the connection, worked with me.
I'm trying to run a client-server program in java on Netbeans.
Here's the code for the server:
// 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]); #line 48, error arises here.
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Here's the code for the client:
// File Name GreetingClient.java
import java.io.*;
import java.net.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0]; #line 10, error arises here
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();
}
}
}
So when I want to simulate the client and the server running together I first run the server.
Once the server is running I need to run the client.
However when I try to run the server file, I get the following error:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingServer.main(GreetingServer.java:48)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Similarly, when I try to run the client program, I get the following error:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingClient.main(GreetingClient.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Why is this happening? Please help.
UPDATE:
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
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)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
// File Name GreetingClient.java
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, 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)
{
}
}
}
There is no error on the server side now. But I am still getting the following error on the client side:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingClient.main(GreetingClient.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Your code supposes that you pass the port you want to use as an argument so :
Either you run your application with the line Patryk RoszczyniaĆa posted
If you don't want to use it, just delete the lines :
String serverName = args[0];
int port = Integer.parseInt(args[0]);
and replace them by hardcoded values like :
String serverName = "MyServerName";
int port = 3000;
Update :
I just tested your code, in fact, the serverName is the address you use to connect to the server, so replace it by "localhost" if you are running both client and server on the same machine.
Tested code :
Here is the updated code I tested and it should work perfectly if you run both on the same machine.
Client :
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "localhost";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, 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)
{
}
}
}
Server :
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
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)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
To run SocketServer you need to pass port on which server will work. For example:
SocketServer server = new SocketServer(1234);
The problem is that you want to pass port by java argument and you aren't doing that. First of all before use of any variable you should first validate it.
if (args.length>0) {
int port = Integer.parseInt(args[0]); #line 48, error arises here.
}
Your program requires params but I think that you probably run your program without params.
You should run program in this way: java -jar app.jar 1234
But you do it in this way: java -jar app.jar
In this article you will find how to pass parameters to java program using netbeans http://netbeanside61.blogspot.com/2009/02/using-command-line-arguments-in.html.
If you are new in java you should first read this tutorial http://docs.oracle.com/javase/tutorial/networking/sockets/. It's very helpful.