I'm trying to write a simple proxy server, and I found this code online and I just want to try to run it see if it works, but when it creates a new socket, it got an ConnectException that says Connect refused. I'm using 'localhost' as the host and I tried several different ports but nothing works. What's the problem here, is it the code or my machine?
public static void runServer(String host, int remotePort, int localPort) throws IOException {
// Create the socket for listening connections
ServerSocket mySocket = new ServerSocket(localPort);
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
client = mySocket.accept();
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
try {
server = new Socket(host, remotePort);
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":"
+ remotePort + ":\n" + e + "\n");
out.flush();
client.close();
continue;
}
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
}
};
t.start();
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
'Connection refused' means exactly one thing: nothing was listening at the IP:port you tried to connect to. So it was wrong. The solution is to get it right, or to start the server if it hadn't been started.
You need to set timeout while reading data from socket, there is an example available here
Related
I need a Java Proxy Server that let me connect to [localhost:9318] through [localhost:9418], like:
[my browser] -> [localhost:9418] -> [localhost:9318]
for that I tried this code:
http://www.java2s.com/Code/Java/Network-Protocol/Asimpleproxyserver.htm
package com.example.proxyserver;
import java.io.*;
import java.net.*;
public class App {
public static void main(String[] args) throws IOException {
try {
String host = "localhost";
int remoteport = 9318;
int localport = 9418;
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport + " on port " + localport);
// And start running the server
runServer(host, remoteport, localport); // never returns
} catch (Exception e) {
System.err.println(e);
}
}
/**
* runs a single-threaded proxy server on the specified local port. It never
* returns.
*/
public static void runServer(String host, int remoteport, int localport) throws IOException {
// Create a ServerSocket to listen for connections with
ServerSocket ss = new ServerSocket(localport);
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// Make a connection to the real server.
// If we cannot connect to the server, send an error to the
// client, disconnect, and continue waiting for connections.
try {
server = new Socket(host, remoteport);
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
out.flush();
client.close();
continue;
}
// Get server streams.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// a thread to read the client's requests and pass them
// to the server. A separate thread for asynchronous.
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Read the server's responses
// and pass them back to the client.
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
}
catch (IOException e) {
}
}
}
}
}
This code works but it is very slow.
Do you know what do I need to do in order to increase the speed?
Or maybe do you know about another Java Proxy Server code that be fast?
Thanks!
The client send a message, then the server receives the message and response the message. I don't know why the client can not read the response. If I remove the read part in client, the server can get the message. However for the following code, nothing work. Also I tried the flush(), it still doesn't work.
For client
public void run() {
try (Socket echoSocket = new Socket(HOSTNAME, Integer.parseInt(PORTNUMBER));
DataOutputStream dOut = new DataOutputStream(echoSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(echoSocket.getInputStream());
) {
while (true) {
command = UI.commandQueue.take()
dOut.writeInt(Message.toByteArray(command).length);
dOut.write(Message.toByteArray(command));
int length;
while((length = dIn.readInt()) != 0) {
if (length > 0){
byte[] messagebyte = new byte[length];
dIn.readFully(messagebyte, 0, messagebyte.length);
try {
msg = Message.fromByteArray(messagebyte);
testDisplay(msg);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
testDisplay(msg);
}
}
}
}catch (UnknownHostException e) {
UI.display("Don't know about host " + HOSTNAME);
} catch (IOException e) {
UI.display("Couldn't get I/O for the connection to " + HOSTNAME);
}
}
For server
public void run() {
try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT_NUMBER));
Socket clientSocket = serverSocket.accept();
DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());) {
int length;
while ((length = dIn.readInt()) != 0) {
if (length > 0) {
byte[] messagebyte = new byte[length];
dIn.readFully(messagebyte, 0, messagebyte.length); // read the
// message
Message msg;
try {
msg = Message.fromByteArray(messagebyte);
testDisplay(msg);
dOut.writeInt(Message.toByteArray(msg).length);
dOut.write(Message.toByteArray(msg));
UI.display("ack sent");
} catch (Exception e) {
// TODO Auto-generated catch block
UI.display(e.getMessage());
}
}
}
} catch (IOException e) {
UI.display(
"Exception caught when trying to listen on port " + PORT_NUMBER + " or listening for a connection");
UI.display(e.getMessage());
}
}
Your server is echoing one response per request, but your client is trying to read more than one response per request, which it will never get, so it blocks.
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
I am doing a sample client-server socket project where the server sends a file to the client and the client saves it in a destination folder. It works well BUT it only works ONCE. I have to restart the server and reconnect the client in order to send another file.
What am I doing wrong?
Server:
public void doConnect() {
try {
InetAddress addr = InetAddress.getByName(currentIPaddress);
serverSocket = new ServerSocket(4445, 50, addr);
isServerStarted = true;
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
String command = inputStream.readUTF();
this.statusBox.setText("Received message from Client: " + command);
} catch (IOException e) {
e.printStackTrace();
}
}
Method that I use to send the file from server
public void sendFile() {
fileEvent = new FileEvent();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
//Now writing the FileEvent object to socket
try {
outputStream.writeUTF("newfile");
outputStream.flush();
outputStream.writeObject(fileEvent);
String result = inputStream.readUTF();
System.out.println("client says: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
Client
public void connect() {
int retryCount = 0;
while (!isConnected) {
if (retryCount < 5) {
try {
socket = new Socket(currentIPAddress, currentPort);
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
isConnected = true;
//connection success
String command = inputStream.readUTF();
if (command.equals("newfile")) {
this.clientCmdStatus.setText("Received a file from Server");
outputStream.writeUTF("Thanks Server! Client Received the file");
outputStream.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
new Thread(new DownloadingThread()).start();
}
} catch (IOException e) {
e.printStackTrace();
retryCount++;
}
} else {
//Timed out. Make sure Server is running & Retry
retryCount = 0;
break;
}
}
}
Code used for downloading file in client
public void downloadFile() {
try {
fileEvent = (FileEvent) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = destinationPath + fileEvent.getFilename();
if (!new File(destinationPath).exists()) {
new File(destinationPath).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
serverResponsesBox.setText("File received from server: " + fileEvent.getFilename());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
In order to get the server accept another (and more) connections, you have to put it into a loop
while(someConditionIndicatingYourServerShouldRun) {
Socker socket = serverSocket.accept();
//respond to the client
}
I'd recommend using a thread pool and submit the processing to the thread pool, i.e. by using an ExecutorService. Further, you should close Resources such as stream when finished, the "try-with-resources" construct helps you with that. So your code might look like this
ServerSocket serverSocket = ...;
ExecutorService threadPool = Executors.newFixedThreadPool(10);
AtomicBoolean running = new AtomicBoolean(true);
while(running.get()) {
Socket socket = serverSocket.accept();
threadPool.submit(() -> {
try(ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
OutputStream os = new ObjectOutputStream(socket.getOutputStream())) {
String command = is.readUTF();
if("shutdown".equals(command)) {
running.set(false);
} else {
this.statusBox.setText("Received message from Client: " + command);
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
This is my code:
import java.io.*;
import java.net.*;
public class proxy {
public static void main(String[] args) throws IOException {
try {
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(0);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.err.println(e);
}
}
/**
* runs a single-threaded proxy server on
* the specified local port. It never returns.
*/
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
// Create a ServerSocket to listen for connections with
System.out.println("Connected to Client!");
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
System.out.println("Client Accepted!");
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// Make a connection to the real server.
// If we cannot connect to the server, send an error to the
// client, disconnect, and continue waiting for connections.
try {
server = new Socket(host, remoteport);
System.out.println("Client connected to server.");
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":"
+ remoteport + ":\n" + e + "\n");
out.flush();
client.close();
System.out.println("Client disconnected");
continue;
}
// Get server streams.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// a thread to read the client's requests and pass them
// to the server. A separate thread for asynchronous.
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Read the server's responses
// and pass them back to the client.
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
When I run it I get to the message "Connected to client" (line 40) but after that nothing is happening in the window. I don't get the "Client has connected to the server message" so I assume the problem is somewhere around there?
Why is this happening? Does anyone know a fix?
I'm very new to java so please don't be harsh on me.
Your "Connected to Client!" message is misleading. At that point, you are starting your server and clients will soon be able to connect, but no clients have connected yet. Your program is waiting for
client = ss.accept();
to return. ServerSocket.accept waits for a connection to be made across the port. You need another thread, program, or computer to connect to this port to begin hosting them as a client. Make sure that this other thread, program, or computer is properly configured to connect to your open port. You likely need to either set ServerSocket to use a fixed port, or to determine what port it has opened a socket on and tell your other program what port to use.
I am facing problem in Java socket communication, I am running Live555 Media Server and one small app (some what similar to proxy server code, referred one online code snippet) in one machine, and also created one client code and running in my laptop. All machines are in same network. When I send RTSP Command from client to proxy, It is receiving properly and it is redirecting that received command to Live555 server and its getting back proper response but the response is not receiving in client. Help me to fix this problem and also suggest me some doc link to understand the problem.
here is my proxy code,
public class TestProxyServer {
public static void main(String[] args) {
try {
String host = "127.0.0.1";
int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting proxy for " + host + ":" + serverPort
+ " on port " + proxyPort);
runServer(host, serverPort, proxyPort);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sProt, int pPort) throws IOException {
ServerSocket ss = new ServerSocket(pPort);
final byte[] request = new byte[1024];
byte[] replay = new byte[1024];
while(true) {
Socket server = null, client = null;
try {
client = ss.accept();
final InputStream fromClient = client.getInputStream();
final OutputStream toClient = client.getOutputStream();
// for Live555
try {
server = new Socket(host, sProt);
} catch(Exception e) {
PrintWriter out = new PrintWriter(toClient);
out.print("Proxy can not connect to Live555 on host " + host + " with the port " + sProt + "\n");
out.flush();
client.close();
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String ClientMSG;
while((bytesRead = fromClient.read(request)) != -1) {
toServer.write(request, 0, bytesRead);
ClientMSG = new String(request, 0, bytesRead);
System.err.println("From Client : " + ClientMSG);
toServer.flush();
}
} catch(Exception e) {
try {toServer.close();} catch(IOException ioe){}
}
}
};
t.start();
int bytesRead;
try {
String toCMSG;
while((bytesRead = fromServer.read(replay)) != -1) {
toClient.write(replay, 0, bytesRead);
toCMSG = new String(replay, 0, bytesRead);
System.err.println("Response from Live555 " + toCMSG);
toClient.flush();
}
} catch(Exception e) {
toClient.close();
// e.printStackTrace();
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(server != null)
server.close();
if(client != null)
client.close();
}
}
}
}
and client code is here,
public class Test {
public static void main(String[] args) {
try {
String host = "192.168.1.9";
// int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting Client to connect proxy on " + host + ":" + " with port " + proxyPort);
runServer(host, proxyPort);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sPort) throws IOException {
final byte[] request = new byte[1024];
final byte[] reply = new byte[1024];
while (true) {
Socket server = null;
try {
// for Proxy
try {
server = new Socket(host, sPort);
} catch (Exception e) {
System.out.println("Proxy can not connect to ProxyServer on host " + host + " with the port " + sPort + "\n");
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
int bytesRead;
try {
String RtspMSG = "DESCRIBE rtsp://192.168.1.9:8554/free.ts RTSP/1.0\r\nCSeq: 2\r\n\r\n";
// while((bytesRead = fromClient.read(RtspMSG.getBytes()))
// != -1) {
toServer.write(RtspMSG.getBytes(), 0, RtspMSG.length());
System.err.println("Sent : " + RtspMSG);
toServer.flush();
// }
} catch (Exception e) {
try {
toServer.close();
} catch (IOException ioe) {
}
}
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String response = null;
System.err.println("----------------------------------");
while ((bytesRead = fromServer.read(reply)) != -1) {
response = new String(reply, 0, bytesRead);
}
System.err.println("Response from Proxy : "
+ response);
} catch (Exception e) {
try {
fromServer.close();
} catch (Exception e1) {
}
// e.printStackTrace();
}
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (server != null)
server.close();
}
}
}
}
Thank You