I am trying to connect a client application to my code through port 8000 on my pc offline. I am using the ServerSocket library to connect using the below code. The client's application sends XML messages across the port and I need to connect, interpret and respond. (Please bear in mind that I haven't coded interpret/respond yet when reading the below).
Every time I try to send a message from the client application (when running the debug feature in eclipse), the code gets to the serverSocket.accept() method which should be the 'handshake' between client and server and can't go any further. I am unable to change the client application obviously so need to figure out why it's not accepting the connection.
package connect;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class PortListener2 {
public static void main(String[] args){
System.out.println("> Start");
int portNumber = 8000;
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: "+inputLine);
out.println(inputLine);
if (inputLine.equals("exit")){
break;
}
}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("Disconnected");
}
}
}
Related
I have written a simple Java TCP Server and a Client (See below).
The idea is quite simple: the Client sends a message to the Server the Server reads it, modify it and sends it back to the client.
import java.io.*;
import java.net.*;
public class ServerTest2 {
public static void main(String[] argv) {
try {
ServerSocket serverSocket = new ServerSocket(2000); // Create Socket and bind to port 2000
System.out.println("Created");
Socket clientSocket = serverSocket.accept(); //Wait for client and if possible accept
System.out.println("Connection accepted");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); // for outputs
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // for inputs
String request; // requst/input of client
String answer; // the answer for the client
System.out.println("Start Waiting");
request = br.readLine(); //Wait for input from client
answer = "answer to "+request;
bw.write(answer); // Send answer to client
System.out.println("send");
bw.newLine();
bw.flush();
//Shut everything down
bw.close();
br.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
The Client Implementation
import java.io.*;
import java.net.*;
public class ClientTest2 {
public static void main(String[] argv) {
try {
String host = "185.75.149.8"; //public ip of router
Socket clientSocket = new Socket(host,2000); //Create and connect Socket to the host on port 2000
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); // for outputs
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // for inputs
String answer;
String request = "HelloWorld";
bw.write(request); //Write to server
bw.newLine();
bw.flush();
System.out.println("Waiting");
answer = br.readLine(); //Wait for answer
System.out.println("Host = "+host);
System.out.println("Echo = "+answer);
//Shut eveything down
bw.close();
br.close();
clientSocket.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
It works perfectly on my local network.
Now I want to use it via the Internet so I installed Port Forwarding on Port 2000 in my Router which sends it to Port 2000 of my PC.
My PC is directly connected to my Router without any Subnets in between.
The Problem is that the Server does not accept the connection(Stops at serverSocket.accept()).
It does not throw an Exception it just waits forever.
The Client does also not throw an Exception (If the Port isn't open it would throw a Connection refused Exception)
This means that the Port Forwarding should work (I have also tested whether the port is open with a Webtool (its open)).
But strangely the Client stops waiting after about 10 seconds and continues with the program.
Since the Port Forwarding should work and my Code works fine in my local Network I absolutely don't know how or where I could find the problem.
I appreciate any help.
Thank you very much!
I am writing my first Client-Server program in Java using Sockets. I am using Eclipse as the IDE. When I am testing the communication between both programs (server and client) I run first the server using the command prompt and then I run the client in Eclipse. Everything works fine, I can read from and write to the socket, however, when I close the client program in Eclipse, the server program closes too. Why is this happening? The server is supposed to be running by itself in the command prompt, it is not dependent on a client.
Also I would like to know if there is any possibility I can run both programs in Eclipse instead of opening the server in the command prompt first.
Here is my code for both programs:
Server:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerPrg {
public static void main(String[] args) {
System.out.println("Server is running.....");
try {
ServerSocket socketSer = new ServerSocket(4444);
Socket clientSocket = socketSer.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = (new BufferedReader (new InputStreamReader(clientSocket.getInputStream())));
BufferedReader stdIn = (new BufferedReader (new InputStreamReader(System.in)));
System.out.println("Client: " + in.readLine());
String input ;
while((input = stdIn.readLine()) != null)
{ out.println(input);
System.out.println("Client: " + in.readLine());
}
}
catch (Exception e) {System.out.println("CAN'T CREATE SERVERSOCKET. PROBABLY THE PORT IS BEING USED " + e);}
} //end main
} //end public class
Client:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientPrg {
public static void main(String[] args) {
int portNumber = 4444;
try {
Socket clientSocket = new Socket("127.0.0.1", portNumber);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String input;
while ((input = stdIn.readLine()) != null)
{
out.println(input);
System.out.println("Server: " + in.readLine());
}
} catch(Exception e)
{
System.out.println(e);
System.out.println("CAN'T CONNECT TO THE SERVER");
}
} //end main
} // end public class
Your server lacks a loop around accepting client sockets.
This means that after your client socket is accepted, it will exit because there is no flow control element that will have it attempt to accept a second client socket.
A simple loop around accepting client sockets is probably not exactly what you want. That is because there will be only one Thread in the solution, which means that while a client is being handled, other clients won't be able to be accepted.
There are many ways to handle the situation above. One of the simplest is to create a thread for every accepted client to handle the client's communications. While this is initially simple, it does not scale very well. With a large number of clients, the thread count will rise, and most computers can handle many more network connections than threads.
The scope of talking about services that scale well is far to big to address here; but, after you get familiar with one thread per client processing, start looking at Java NIO.
I'm working on an web based API for a BungeeCord Server but after opening the ServerSocket on Port 8082 the BungeeCord on Port 25565 isn't available furthermore.
This class is opening the ServerSocket:
package de.pardrox.bungeeapi;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTP {
static router router = new router();
public static void main(int args) {
try {
int port = args;
#SuppressWarnings("resource")
ServerSocket apiweb = new ServerSocket(port);
for (;;) {
Socket client = apiweb.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
out.print("HTTP/1.1 200 \r\n");
out.print("Content-Type: text/plain\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
String line;
InetAddress ip_client = client.getInetAddress();
main.syslog("Request of client "+ip_client.toString());
while ((line = in.readLine()) != null) {
if (line.length() == 0)
break;
if(line.toLowerCase().contains("GET".toLowerCase()))
{
String url = line.replace("GET ", "").replace(" HTTP/1.1", "");
out.print(router.get(url));
}
}
out.close();
in.close();
client.close();
}
}
catch (Exception e) {
System.err.println(e);
System.err.println("Call HTTP(<port>)");
}
}
}
Does anyone have an idea why opening the ServerSocket seems to close the Socket of the Gameserver? Eclipse doesn't find any error and the gameserver itself seems to run fine. The API is reachable also without any trouble.
For completeness:
I've startet the socket class with HTTP.main(8082);
I think there's a mistake at for (;;).
This will create an infinite loop that will run for ever....
Maybe this will cause the Main Thread of BungeeCord server to stop responding.
Try removing the for (;;) and using this code below instead of just running the code in the Default BungeeCord Thread. Since BungeeCord doesn't allows you to create custom Threads, the only way to do this is using the Scheduler and running a Runnable asynchronous.
ProxyServer.getInstance().getScheduler().runAsync(yourPluginHere, new Runnable() {
#Override
public void run() {
// Put your code here
}
});
I'm trying to learn about client/server and sockets right now but I'm confused on the bigger scope of things. I followed a tutorial that has a client as an android app and the server is a java application. I run both of them on eclipse fine.
My question now is how do I make this global? So I'll take my server code written in java, export it to a text called server.java, and then upload it to my personal site? And then when I start my client android app, I'll make a call to say http://blah.com/server.java to start my server, right? Then my server will begin listening on that port and my client can connect to it?
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleTextServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println(message);
//will later add an output stream to write back to android
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
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.