Java - Can't Connect With ServerSocket - java

I am trying to use ServerSocket with port 2649, and other people cannot connect. It works fine with localhost. This is the error people get when trying to connect:
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Client.main(Client.java:11)
I have port forwarded, and I do not have a firewall active on my computer. Here are the settings I used when port forwarding.
http://i.imgur.com/NLdaA.png
http://i.imgur.com/FJpJQ.png
When I check port 2649 on canyouseeme.org, it says the connection timed out.
I am using Windows XP too. Any help is appreciated.
Thanks
EDIT: Here is the code I am using
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args)throws Exception {
System.out.println("Starting...");
File file = new File("C:/Testing.txt");
InputStream in = new FileInputStream(file);
ServerSocket server = new ServerSocket(2649);
System.out.println("Ready for connection");
Socket socket = server.accept();
OutputStream output = socket.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(output);
out.writeObject("C:/Testing.txt");
byte[] buffer = new byte[socket.getSendBufferSize()];
int bytesReceived = 0;
while ((bytesReceived = in.read(buffer)) > 0) {
output.write(buffer, 0, bytesReceived);
}
out.flush();
out.close();
in.close();
server.close();
socket.close();
output.flush();
output.close();
System.out.println("Finished");
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
System.out.println("Starting...");
Socket socket = new Socket("IP ADDRESS", 2649);
InputStream input = socket.getInputStream();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
FileOutputStream out = new FileOutputStream(new File((String) in.readObject()));
byte[] buffer = new byte[socket.getReceiveBufferSize()];
int bytesReceived = 0;
while ((bytesReceived = input.read(buffer)) > 0) {
out.write(buffer, 0, bytesReceived);
}
in.close();
out.close();
input.close();
socket.close();
System.out.println("Finished");
}

if it's not the firewall. make sure you bind the server socket to 0.0.0.0 and not to localhost.
try calling server.bind(new InetSocketAddress("0.0.0.0", port));

"Connection timed out" -> a firewall discards packets. Most likely Windows Firewall - try disabling it and see if they can connect.

Related

Java.lang.ClassNotFoundException on ObjectInputStream.readObject() when sending objects from Android to Java Server [duplicate]

This question already has answers here:
Android ClassNotFoundException
(9 answers)
Closed 4 years ago.
I am working in an Android App and I need to send serialized objects (mainly from a Client class) between the Android Client and a Java Server.
I am using ObjectInputStream and ObjectOutputStream to send the objects through a web socket, but when reading the object in the server it seems like it is trying to cast it as the Client class from the Android package instead of the server package.
Here is a simplified code of what I am calling in my main Activity in Android:
package com.example.razer.clienttest;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MessageSender extends AsyncTask<Void,Void,Void> {
ClienteFree cliente = new ClienteFree();
String test = "Testing this crap";
static String ip = ""; //This is where I'm putting my IP
#Override
protected Void doInBackground(Void...voids){
try{
Socket s = new Socket(ip,7000);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
//oos.writeObject(test);
oos.writeObject(cliente);
oos.flush();
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
//String Test2 = (String) ois.readObject();
ClienteFree cliente2 = (ClienteFree)(ois.readObject());
is.close();
ois.close();
os.close();
oos.close();
s.close();
}catch(Exception e){
System.out.println(e);
}
return null;
}
}
And my server implementation:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Server {
static List<ClienteFree> clientes = new ArrayList<ClienteFree>();
ClienteFree client = new ClienteFree("Null","Null","Null","null");
String Test = "Testing this crap again";
public static final int PORT = 7000;
public static void main(String[] args) throws IOException, ClassNotFoundException {
try {
new Server().runServer();
} catch (Exception e) {
e.printStackTrace();
}
}
public void runServer() throws Exception {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up and ready for connection...");
Socket socket = serverSocket.accept();
System.out.println("Connection succesful");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//String Test2 = (String) ois.readObject();
client = (ClienteFree)(ois.readObject());
//System.out.println(Test2);
doSomething(client);
//oos.writeObject(Test);
oos.writeObject(client);
oos.flush();
ois.close();
oos.close();
socket.close();
serverSocket.close();
}
private void doSomething(ClienteFree client){
clientes.add(client);
System.out.println(client.getName());
client.setName("Poncho");
}
}
The error shows that the server is trying to find the class in the Android package com.example.razer.clienttest.ClienteFree (my android package) instead of the server one. Does anybody know how to solve this issue or the correct way to send objects between Android and Java servers if the object will contain lists of Observable type objects within it?
I have tried serializing the Client objects to a MySQL database from my server using the SQL libraries and it worked, but I haven't found a proper way to do it in Android.
This is the error I'm getting:
Server up and ready for connection...
Connection succesful
java.lang.ClassNotFoundException: com.example.razer.clienttest.ClienteFree
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Server.runServer(Server.java:54)
at Server.main(Server.java:15)
Thank you!
The class you sent does not exist on the CLASSPATH at the receiving end.
You can't deploy a similar class in a different package and expect it to be the same as the original class in the original package. It isn't.

Exception in "helloworld" server and client program in socket programming

I am getting this error when I'm running my client program. I was unable to recognise the problem yet.I've changed the port numbers but there is no use. I saw the previous posts regarding the same error but I didn't figured it out.
Server.java
import java.io.*;
import java.net.*;
class Server{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(8080);
while (true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Client.java
import java.io.*;
import java.net.*;
class Client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
I am getting an error when I run the client.java
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Client.main(Client.java:11)
Can anyone help with this error?
The Client and Server Program runs perfectly fine for me.
Can you check if there is some process already listening on that port.

Client/Server Program: Connection Reset

I have written a basic program to demonstrate client server interaction. Connection is getting established but unable to fetch the data from stream. It throws an exception stating the connection reset
Server
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private ServerSocket serverSocket;
private int port;
public SocketServer(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for clients...");
Socket client = serverSocket.accept();
sendWelcomeMessage(client);
}
private void sendWelcomeMessage(Socket client) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
}
/**
* Creates a SocketServer object and starts the server.
*
* #param args
*/
public static void main(String[] args) {
// Setting a default port number.
int portNumber = 9990;
try {
// initializing the Socket Server
SocketServer socketServer = new SocketServer(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient {
private String hostname;
private int port;
Socket socketClient;
public SocketClient(String hostname, int port){
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Attempting to connect to "+hostname+":"+port);
socketClient = new Socket(hostname,port);
System.out.println("Connection Established");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.println("Response from server:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketClient client = new SocketClient ("localhost",9990);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up."+e.getMessage());
e.printStackTrace();
}
}
}
##OUTPUT##
Attempting to connect to localhost:9990
Connection Established
Response from server:
Hello. You are connected to a Simple Socket Server. What is your name?
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at SocketClient.readResponse(SocketClient.java:31)
at SocketClient.main(SocketClient.java:45)
There's at least one thing wrong with the current implementation. You utilise readLine() to get the data - however readLine() does this:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Your program that emits the data does not use a newline character to terminate the "message":
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
To terminate the message, add a newline:
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.write("\n"); // shown separately for clarity
writer.flush();
I have actually been wrestling with this for a while as well, but I believe I have found a more accurate answer, and thought I should share it. The original example never closes the BufferedWriter. So simply add writer.close() after writer.flush(), like so:
writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
writer.flush();
writer.close();
Because it was never closed, the output was never null, so the while loop was never failing.

How to enable the firewall and the router privileges to send Files using Sockets in java?

I've been working on a Swing application and when i wanted to add an option, where the user can send files via the local network, i had faced some serious problems.
To send the files through the network, i used the Sockets library to create a connection between the client and the server, the Source Code of Client.java is :
package Test;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
Socket sock = null;
try{
sock = new Socket("192.168.1.107",1234);
}catch(Exception e){
e.printStackTrace();
e.getCause();
}
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Test\\test-copy.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
sock.getPort();
}
}
and the Source Code of Server.java is :
package Test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server{
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(1234);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
//servsock.set
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("C:\\testing\\test.txt");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
As you can see, i want to send a test.txt file from my computer to another computer that exists in the local network. when i run the Server.Java and the Client.java i get an exception in the terminal mentioning that the Connection is timed out :
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
Connecting...
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 Test.NewClass1.main(Client.java:27)
Exception in thread "main" java.lang.NullPointerException
at Test.Client.main(Client.java:36)
And what confused me more is that when i run the application using my Localhost , the copy of the file test-copy.txt is well created, i have looked for the reasons of the exception, i found that it might be the Firewall privileges, and i enabled transactions for the port : 1234 but i still got the same error.
What i am asking for here is, is it a matter of authorities or privileges?, if yes what am i suppose to set as a configuration to the firewall, or the router to enable transactions?
my computer is set as an administrator and the destination too, i am using Windows 7 as an Operating system
I hope that i made my question clear.
Thank you :).

Sockets won't work in network

I am working on an application that sends files via the network.
I used 2 classes to send and to receive the file that I selected.
The problem that I have faced, when I am working on localhost, is that the process goes correctly, but when I change the IP address to the network IP, it does not work.
Here is the two classes that I am using.
Class Server :
package Test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server{
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(41111);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("C:\\Users\\Marrah.Zakaria\\Desktop\\test\\test.txt");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
Class Client:
package Test;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
Socket sock = new Socket("192.168.1.100",41111);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Test\\test-copy.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
sock.getPort();
}
}
after running an exception shows up :
Exception in thread "main" java.net.ConnectException: Connection timed out: 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)
Please would you tell me what shall i do to get rid of it.
I dis-activated the receivers firewall a different exception occurred :
Exception in thread "main" java.net.ConnectException: Connection refused: 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)
If you start up the server, can you telnet to this combination ?
telnet 192.168.1.100 41111
That'll tell you immediately if you have a routing issue (telnet will refuse to connect)
also try to ping 192.168.1.100 from the machine where you are running the client (i.e from the command prompt if you are in windows box)
Have you check if there is any firewall blocking the custom port (41111) on your network (also check Windows firewall)?
This is the first thing to check when you have a timeout.

Categories

Resources