Sockets won't work in network - java

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.

Related

Not sending XML command with fixed header via TCP/IP using Java

I'm new to Java (basically had to learn it on the fly for this project), but I'm trying to send an XML command to a server to get some data from it. To do this, I've written a Java program and I'm running it from the command line.
Here's my Java code for a reference. I got most of this from a client/server TCP tutorial and adjusted the IP, port, and outgoing message accordingly. Again, I'm very new to this, so any help is appreciated.
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.BufferedInputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class GDC {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
System.out.println("Attempting connection to GE Reuter Stokes");
// establish the socket connection to the server
// using the local IP address, if server is running on some other IP, use that
Socket socket = new Socket(<SERVER_IP>, <SERVER_PORT>);
System.out.println("Socket Connected");
// write to socket using OutputStream
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
// Initializing request content
byte[] request = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><command version=\"2.2\" cmd=\"HEARTBEAT\"/>".getBytes(StandardCharsets.UTF_8);
// DataOutputStream.writeInt() writes in big endian and
// DataInputStream.readInt() reads in big endian.
// using a ByteBuffer to handle little endian instead.
byte[] header = new byte[5];
ByteBuffer buf = ByteBuffer.wrap(header, 1, 4);
buf.order(ByteOrder.LITTLE_ENDIAN);
// Initializing request header
header[0] = (byte) 0x060E2B34;
header[1] = (byte) 0x02050101;
header[2] = (byte) 0x0F150111;
header[3] = (byte) 0x00000000;
buf.putInt(request.length);
System.out.println("Sending request to Socket Server");
// Sending request
dos.write(header);
dos.write(request);
dos.flush();
System.out.println("Request was sent. Awaiting response.");
// read from socket using InputStream
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
// Read response header
dis.readFully(header);
buf.flip();
// Read response content
byte[] response = new byte[buf.getInt()];
dis.readFully(response);
// convert the content into a string
String message = new String(response, StandardCharsets.UTF_8);
System.out.println("Message: " + message);
// close your resources
dis.close();
dos.close();
socket.close();
Thread.sleep(100);
}
}
I want to send XML request using the following instruction :
I got an error like follow:
Attempting connection to GE Reuter Stokes
Socket Connected
Sending request to Socket Server
Request was sent. Awaiting response.
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at java.io.DataInputStream.readFully(DataInputStream.java:195)
at java.io.DataInputStream.readFully(DataInputStream.java:169)
at GDC.main(GDC.java:54)

What port should I use for file writing to file on a server? using Socket

Using a Socket to establish connection to my school linux server account. Main idea, connect to server and write text from desktop to an existing file on the server.
I only can find Java doc examples of how to send data from server to desktop, I'm not sure if they are the same for both.
Don't know enough about computer networking, so Im unsure
1 what values to pass to the constructor Socket(String host, int port)
Would the host name be host = "myaccount#myserver.com" or host = "myserver.com" ?
2 what port should I use to stream string/text data to the file on the server?
it's a simple java file transfer
Server
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 Main {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(12345);
File myFile = new File("freeman.txt");
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
Client
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 12345);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("freeman.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
As you can see instead of 127.0.0.1(localhost) you can write your server, like myserver.com and instead of port, you can add your port

Exception in thread "main" java.net.ConnectException: Connection refused: connect [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying make a socket conection and send a file inside my windows 7 with netbeans but I get this error:
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:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
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 socket.TCPclient.main(TCPclient.java:22)
Java Result: 1
This is my server class:
package socket;
import java.net.*;
import java.io.*;
public class TCPserver {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("source.pdf");
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();
}
}
}
and this is my client class:
package socket;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.*;
import java.io.*;
public class TCPclient{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source-copy.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
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();
}
}
How can I fix this problem, Thank you?

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 :).

Java - Can't Connect With ServerSocket

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.

Categories

Resources