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.
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!
I am trying to write a simple TCP server, but the problem I have is that the socket gets closed after the first run (it's running in a thread, by the way). I could try rewriting it without ARM (Automatic Resource Management), that bock in round squares after try - but I would rather keep it.
So, it there a way to write a simple persistent TCP server by using ARM in Java?
public class Server {
/* Server */
public int port = 8088;
public Server (int port){
this.port = port;
System.out.println("Will listen on port " + this.port);
}
public Server () {
System.out.println("Will listen on default port " + port);
}
public void start() {
try (ServerSocket initSocket = new ServerSocket(port);
Socket socket = initSocket.accept();
BufferedReader bfin =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream bfout =
new BufferedOutputStream(socket.getOutputStream())
)
{
String line = bfin.readLine();
while (line != null && !"BYE\n".equals(line)){
String answer = parseadd(line) + "\n";
System.out.println("From client: " + line);
bfout.write(answer.getBytes());
bfout.write("BYE\n".getBytes());
bfout.flush();
line = bfin.readLine();
}
System.out.println("Exiting server while loop!");
}
catch (IOException e) {
System.out.println("Exception caught when trying to");
System.out.println(e.getMessage());
}
}
}
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
I want to read and write byte[] data with a socket, but I cannot stop the stream.
This is my server:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Server side");
DataInputStream in;
DataOutputStream out;
ServerSocket servers = null;
Socket fromclient = null;
// create server socket
try {
servers = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Couldn't listen to port 4444");
System.exit(-1);
}
try {
System.out.print("Waiting for a client...");
fromclient = servers.accept();
System.out.println("Client connected");
} catch (IOException e) {
System.out.println("Can't accept");
System.exit(-1);
}
in = new DataInputStream(fromclient.getInputStream());
out = new DataOutputStream(fromclient.getOutputStream());
String input = "", output;
System.out.println("Wait for messages");
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
byte[] mass = "some data".getBytes("UTF-8");
out.write(mass, 0, count);
System.out.println(Arrays.toString(bytes));
}
out.close();
in.close();
fromclient.close();
servers.close();
}
}
When I receive data from the client it opens an infinite stream which doesn't stop.
How can I stop this DataInputStream?
Close the connection from the client side (or server side). As long as the connection is open, the server will wait for data to be sent.
In a proper setup you would have a well defined protocol, which could then include shutdown messages to inform the server when the client decides to disconnect. Simply closing the connection is a "raw" way to achieve that, but it's not very elegant.
I'm trying to create a simple multicast communication between my PC (Ubuntu, client) and my phone (Android, server).
Unicast/TCP connections work without any problem, the defined port (37659) opens both on PC and phone. When trying to use a MulticastSocket, no ports get opened. nmap tells me the specified port (36963) is a TCP port and that it is closed. (While the receive-method is being executed).
Am I doing something wrong? Or is the firewall blocking the multicast sockets? (I've tried about 20 different ports and none worked..., currently using port 36963)
EDIT: Also with the firewall completely down, nmap tells me the port is closed...
The server's code (phone):
private void multicastLoop() {
String res = Build.FINGERPRINT + "\n";
final InetAddress group;
final MulticastSocket socket;
final DatagramPacket response;
try {
group = InetAddress.getByName("224.0.0.115");
socket = new MulticastSocket(mport);
socket.setLoopbackMode(true);
socket.setSoTimeout(10000);
socket.joinGroup(group);
response = new DatagramPacket(res.getBytes(), res.length(), group, mport);
} catch (IOException e) {
e.printStackTrace();
return;
}
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while(isRunning) {
try {
byte[] data = new byte[1024];
DatagramPacket dm = new DatagramPacket(data, data.length);
socket.receive(dm);
Log.d("udp", "received");
if (Arrays.equals(dm.getData(), "someone there".getBytes())) {
socket.send(response);
}
} catch (SocketTimeoutException e) {
continue;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.leaveGroup(group);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
The client's code (computer):
public String[] findServers() {
String hello = "someone there";
try {
InetAddress group = InetAddress.getByName(mhost);
MulticastSocket socket = new MulticastSocket(mport);
socket.setLoopbackMode(true);
socket.setSoTimeout(60000);
socket.joinGroup(group);
DatagramPacket p = new DatagramPacket(hello.getBytes(), hello.length(), group, mport);
byte[] buffer = new byte[1024];
socket.send(p);
DatagramPacket r = new DatagramPacket(buffer, buffer.length);
socket.receive(r);
socket.leaveGroup(group);
socket.close();
String srinfo = "";
byte[] data = r.getData();
for (byte b: data)
srinfo += (char) b;
System.out.println("Server found at " + r.getAddress().getHostName() + ": " + srinfo);
} catch (SocketTimeoutException e) {
return new String[] {"timeout"};
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Make sure mhost is set to "224.0.0.115" not some machine name.
Make sure multicast is enabled on your router.
If the host is multi-homed, you need to join the multicast group via all local interfaces, not just the default one, which is what you're doing at present.
You could send the response back to the source address it came from, which is in the received datagram packet. That would also mean that the client doesn't need a MulticastSocket, only a DatagramSocket.