Firewall blocking tcp chat client - java

I wrote small TCP chat client and server. At start running on localhost, and now i moved it to external host. Personally it works alright because i have my firewall disabled, however on another machine it fails getting IOException (at creating Socket). Tried adding port I'm using 9764 to inbound and outbound rules, later disabling firewall at all and it still didn't work getting same IOException. Any thoughts?
Error log: http://pastebin.com/zEbFbX4Y
Client code: https://github.com/karosas/Simple-tcp-chat-client
Exception is catched here:
try {
client = new ChatClient();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(that, "Unknown host exception");
} catch (IOException e) {
JOptionPane.showMessageDialog(that, "IOException");
e.printStackTrace();
}
which leads to ChatClient ->
public ChatClient() throws UnknownHostException, IOException {
server = new Socket(host,port);
out = new PrintWriter(server.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
sc = new ServerConn(server);
}
And it leads to ServerConn
private BufferedReader in = null;
public ServerConn(Socket server) throws IOException {
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
}
public void run() {
String msg;
try {
while((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch(IOException e ) {
System.err.println(e);
}
}
Thanks for anything.

What is happening is that on localhost the connection doesn't need permission to travel through your internet router's firewall but when it connects to a different internet router that router can reject you from the server if it doesn't whitelist that port so you need to go onto the internet router's NetBIOS (The internet router of the server) and then white-list the ports, usually under:
ADVANCED > NAT > VIRTUAL SERVERS/PORT FORWARDING.
For more info on how to do this read the internet routers manual.
EDIT:
What you are doing is trying to connect to a 127.*..** adress meaning it doesn't even go on your network. on server computer rightclick your task bar select task manager go to perforamce tab and select wifi then find the IpV4 address and use that instead of 127.7.13.129

Related

Connect to localhost POP3 server through Thunderbird\Outlook

Trying to connect to my own POP3 server on localhost(1024 port). Its code:
server_socket = new ServerSocket(SBAP_PORT);
Socket clntSocket = server_socket.accept();
public void run() {
try {
try {
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()
));
out = new PrintWriter(socket.getOutputStream(), true);
out.print("+OK\\r\\n");
command = in.readLine();
String result = handleInput(command);
out.println(result);
} finally {
socket.close();
state.close();
System.out.println("client offline.");
}
} catch (Exception ignored) {
}
}
It's working fine with telnet, but when I try to do it with Thunderbird, just get timeout(Failed to find settings for your email account).
In debug I see, that I get null string while connecting.
What am I doing wrong? Maybe I should send something to client just after connecting?
I think it must be \r\n rather \\r\\n, plus try to flush for each response you send to the client by out.flush();, but it might not be necessary.

Receiving data on an application server?

If I make a socket connection from an application that is running on an application server, where does the returned data go? Is it necessary to create a receiving server socket in the application with a specified port, or is it received on the port at which the server is using to connect to the application and I just need to write something that will extract that data?
Here is the code to read from a socket. You are making socket connection to port 8080 in server. You don't have to worry about the OS -> Server port.
public static void readSocket() throws IOException {
try (Socket s = new Socket(InetAddress.getByName(new URL("Some Address").getHost()), 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
}
The socket is one end-point of two-way communication link between server and client programs of the network.
The returned data is sending to your client Socket object, lets call it clientSocket. You need to call clientSocket.getInputStream() to decode it.
No, you dont need to create a receiving server socket in the application. Your client program establishes a connection to the server on your given host and port. clientSocket can both send data to server and receive data from server.
For example the client side code:
private PrintWriter out = null;
private BufferedReader in = null;
public void listenSocket(){
//Create socket connection
try{
clientSocket = new Socket(HOST, PORT);
// use out object to send data to server applicaiton
out = new PrintWriter(clientSocket.getOutputStream(),
true);
// uses in object to receive data from server application
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + HOST);
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}

Android TCP - Socket doesn't get disconnected when app is closed

I'm trying to use TCP with an Android app, so there are two projects, one is the server and one is the client.
When I run the server and open the client, everything works fine and messages are being delivered to both sides, although when I close the app (from an emulator), it won't alert me in the console that the socket connection was closed and attempt to get another connection so when trying to re-open the app, it won't reconnect and messages won't be delivered.
So what am I really doing wrong here? I'm new to Android and TCP, so I'm sorry if this is quite a rookie question.
#Override
public void run() {
super.run();
running = true;
try {
System.out.println("S: Connecting...");
//create a server socket. A server socket waits for requests to come in over the network.
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
//create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
while (running) {
Socket client = serverSocket.accept();
try {
//sends the message to the client
mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
//read the message received from client
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//in this while we wait to receive messages from client (it's an infinite loop)
//this while it's like a listener for messages
while(!client.isClosed()) {
String message = in.readLine();
if (message != null && messageListener != null) {
//call the method messageReceived from ServerBoard class
messageListener.messageReceived(message);
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
It would be more accurate to say that you aren't testing for disconnection correctly.
Socket.isClosed() does not magically become true when the peer disconnects. So using it to control a read loop is futile. It only tells you whether you have closed this socket.
readLine() returns null when the peer has disconnected, but you're treating it as just another value.
A correct loop using readLine() looks like this:
while ((line = in.readLine()) != null)
{
// ...
}

Writing a telnet client in java - how to listen for new data?

I'm attempting to implement a Telnet client in Java, which will just get data from a telnet server.
I've been looking for ages now and have found a lot of things, but not particularly what I need - for example the apache commons client example, which seems to send a lot of commands, which is just confusing me to be honest.
So I therefore thought it would be easier to just to write my own client which connects to the server using a socket.
public class TelnetClient {
private String host;
public TelnetClient(String host) {
this.host = host;
}
public void getData(){
Socket s = new Socket();
PrintWriter s_out = null;
BufferedReader s_in = null;
try {
s.connect(new InetSocketAddress("www.google.com" , 80));
System.out.println("Connected");
//writer for socket
s_out = new PrintWriter( s.getOutputStream(), true);
//reader for socket
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
//Host not found
catch (UnknownHostException e) {
System.err.println("Don't know about host : " + host);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
}
//Send message to server
String message = "GET / HTTP/1.1\r\n\r\n";
s_out.println( message );
System.out.println("Message send");
//Get response from server
String response;
try {
while ((response = s_in.readLine()) != null) {
System.out.println( response );
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I cant actually test this with the server currently so Im just using google.com, however I want to change it to listen continuously for new lines of data on the server.
Basically my question is, am I going about this the wrong way - am I being naive by just using sockets to access the telnet server and am I underestimating what a telnet client/server should be, thanks for any help.
Also if anyone has any good/simple examples of a telnet client, that would be very useful!!
I've been holding off on answering because there are a couple different things going on here -- Google doesn't have a telnet server running on port 80, it's a web (HTTP) server. You're connecting to the webserver with your telnet client and trying to talk over HTTP with plain text. HTTP and telnet are two different protocols.
So there is a mismatch between what you want to do and what these Java telnet clients are designed to do -- namely connect to a remote shell.
Based on what you've been saying, I think you can get it done much more easily by just making an HTTP request. There's a dead simple solution in this answer:
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Sockets are complicated stuff. Take a look at this tutorial if you want to dig deeper in to them. But they're going to be a huge pain to work with and probably not help you get what you need done.

Java SSL sockets not working

I am using TCP/IP sockets to create a client and server applicaton. Originally I was using regular sockets but now I have decided to use SSL for my connection. I have created a keystore and have tried running my application but it has yet to be successful.
Here is my code for the server
public class ArFileServer {
public static void main(String[] args)
{
boolean listening = true;
ServerSocketFactory serversocketfactory;
ServerSocket serverSocket;
try
{
//serverSocket = new ServerSocket(4445);
serversocketfactory = SSLServerSocketFactory.getDefault();
serverSocket = serversocketfactory.createServerSocket(4445);
String keystore = System.getProperty("javax.net.ssl.trustStore");
System.out.println(keystore);
// infinite loop to continually listen for connection requests made by clients
while (listening)
{
new ClientConnection(serverSocket.accept()).start();
if (serverSocket != null)
{
System.out.println("Connection to client established");
}
}
serverSocket.close();
}
catch (IOException e)
{
System.out.println("Error could not create socket connection to port, check that port is not busy");
}
}
}
and here is the client code:
public class ClientSocket
{
SocketFactory socketfactory = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
// establish a connection to All Care's server application through socket 4444 (adjust localhost to reflect the IP address that the server
// is being run from)
public ClientSocket()
{
try
{
//clientSocket = new Socket("localhost", 4445);
//SocketFactory socketfactory = SSLSocketFactory.getDefault();
clientSocket = socketfactory.createSocket("192.168.1.8", 4445);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String truststore = System.getProperty("javax.net.ssl.trustStore");
System.out.println(truststore);
}
catch (IOException e)
{
System.out.println("Could not connect to All Care Server Application : " + e.getMessage());
}
}
}
I am also using these runtime arguments:
-Djavax.net.ssl.keyStore=C:\Users\Chris\Documents\NetBeansProjects\ArFile\keystore.jks -Djavax.net.ssl.keyStorePassword=password
When I try to print out the truststore it always returns null, what am I doing wrong?
When I try to print out the truststore it always returns null
Because you never set it. All you are doing is printing out the value of a system property. If you didn't set it, it is null.
what am I doing wrong?
Nothing yet, except printing out meaningless information. But much of your code doesn't make sense:
if (serverSocket != null)
{
System.out.println("Connection to client established");
}
serverSocket being non-null (a) is inevitable at this point, and (b) doesn't have anything do with the client socket being established, which is inevitable at this point.
catch (IOException e)
{
System.out.println("Error could not create socket connection to port, check that port is not busy");
}
An IOException at this point could mean many things, but the one thing it doesn't mean is 'cannot create socket connection to port'. It is the client that does the connecting: the server accepts connections. When you catch an exception, always print its message, don't just make up your own.
You need to define both trustStore and keyStore in runtime arguments:
-Djavax.net.ssl.keyStore=xxx.ks
-Djavax.net.ssl.keyStorePassword=yyy
-Djavax.net.ssl.trustStore=xxx.ks
-Djavax.net.ssl.trustStorePassword=yyy
Both can be same file.
trustStore contains public keys of others.
keyStore contains own keys and certificates.

Categories

Resources