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.
Related
I am learning networking in Java. I tried a code that uses the ServerSocket class. But the serversocket is not able to establish a connection every time. I tried various port numbers, longer timeouts, but nothing works. Here is my code for the Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
class TestServer extends Thread
{
private ServerSocket serverSocket;
public TestServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(60000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket socket = serverSocket.accept();
System.out.println("Just connected to " + socket.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(socket.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("Thanks for connecting to " + socket.getLocalSocketAddress() + "\nGoodbye!" );
socket.close();
}
catch(SocketTimeoutException e)
{
System.out.println("Socket timed out");
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
}
The TestServer class performs both client and server side operations on the run function being called. I don't get where am I going wrong. My class containing main function is:
import java.io.IOException;
class Main
{
public static void main(String[] args) throws IOException
{
int port = Integer.parseInt(args[0]);
TestServer server = new TestServer(port);
server.start();
}
}
I am new to Java networking, so please be considerate about some silly mistake and let me know what have I done wrong.
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.
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.
I'm a beginner (as you can probably tell) and I'm having issues establishing a connection from my very simple client to my very simple server. My server starts up fine as it creates a serversocket that listens on port 43594. However, when I run my client to try to establish a connection, an IOException is thrown by my client as it tries to connect.
I'm doing java in my spare time as a hobby, so I'd really appreciate if someone could help me understand what's going on, where I'm going wrong (or if I'm even going right any where) so as to help me improve.
Here is my Server code:
package src.org;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.*;
import java.io.*;
public class Server {
private static final Logger logger = Logger.getLogger(Server.class.getName());
private final static void createSocket(int portNumber) throws IOException
{
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public static void main(String... args)
{
logger.info("Starting server...");
Properties properties = new Properties();
logger.info("loading settings...");
try
{
properties.load(new FileInputStream("settings.ini"));
Constants.GAME_NAME = properties.getProperty("name");
Constants.PORT = Integer.valueOf(properties.getProperty("port"));
} catch(Exception ex)
{
ex.printStackTrace();
}
logger.info("Creating sockets...");
try
{
logger.info("Socket created. Listening on port: " + Constants.PORT);
createSocket(Constants.PORT);
} catch(Exception ex)
{
logger.log(Level.SEVERE, "Error creating sockets.", ex);
System.exit(1);
}
}
}
Which (to my knowledge) seems to be doing its job.
And here's what I believe to be the culprit class, the client class:
import java.io.*;
import java.net.*;
public class Client {
//private static final String hostName = Constants.HOST_NAME;
//private static final int portNumber = Constants.PORT;
private static final String hostName = "localhost";
private static final int portNumber = 43594;
public static void main(String... args)
{
try (
Socket socket = new Socket(InetAddress.getLocalHost(), portNumber); // using localhost at the moment
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("Client socket created.");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while((fromServer = in.readLine()) != null)
{
System.out.println("Server:" + fromServer);
fromUser = stdIn.readLine();
if(fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch(UnknownHostException ex) {
System.err.println("Unknown host: " + hostName);
System.exit(1);
} catch(IOException ioe) {
System.err.println("Couldn't get i/o from: " + hostName);
System.out.println("Error:" + ioe.getMessage());
System.exit(1);
}
}
}
When I ping localhost I get a response; the port on both sides is 43594 and the host is just local. The command line response from the client is:
Client socket created
Couldn't get i/o from: localhost
Error: connection reset
Press any key to continue...
I'm sorry in that I know this would be a very simple fix to many of you, but I can't seem to find an answer or fix it myself. Any insight or help would be greatly appreciated. Cheers.
Sorry if I've left out any other important pieces of information.
You've left out much of the code. The part in the server that sends data on the accepted socket. So the method that calls accept() just exits, the socket is garbage-collected, and closed, and the client keeps doing I/O to the other end of the connection, which is invalid,so you get an exception.
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.