I'm a bit new to sockets in Java but here is my question:
I have written a client thread class that will request to connect to a server, created by another application (therefore I do not have a class made for server class). Basically, this application will transmit a certain number of bytes and close the server side of the socket. I have been fully able to receive and process those bytes.
My question is can the client side socket be told to "wait" for another connection from the same address/port to be available and then continue to read bytes? (In essence, I run the application, it reads the bytes and finished, then I run the application again, and the client will still be able to read)
Here is the code for my client thread:
public class ClientThread extends Thread{
private Socket soc;
private InputStream in;
private String host;
private int port;
public ClientThread(String host, int port)
{
this.host = host;
this.port = port;
soc = null;
in = null;
}
public boolean connectToServer()
{
try {
soc = new Socket(host, port);
in = new BufferedInputStream(soc.getInputStream());
System.err.println("Connection accepted: "+soc);
return true;
} catch (UnknownHostException e) {
System.err.println("Unable to determine IP of host: "+host+".");
return false;
} catch (SocketException e) {
System.err.println("Error creating or accessing the socket.");
return false;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: "+host+".");
return false;
}
}
public boolean disconnectFromServer()
{
try {
if(in != null)
in.close();
if(soc != null && soc.isConnected()) {
soc.close();
soc = null;
System.err.println("Connection successfully closed!");
}
return true;
} catch (Exception e) {
System.err.println("Exception: "+e);
return false;
}
}
#Override
public void run() {
try {
int sz = 0;
byte[] tmp = new byte[25];
while(true)
{
if(sz == -1) {
sz = 0;
}
sz += in.read(tmp, sz, 25-sz);
System.out.println(sz);
if(sz == 25) {
tmp = new byte[25];
for(byte b: tmp)
System.out.print(b);
sz = 0;
Thread.sleep(500);
}
}
} catch (SocketException e) {
System.err.println("Connection closed abruptly.");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: "+host+".");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The server will receive a socket when accept() returns, and as long as that socket does not get closed then the connection remains open.
So when you run the application for the first time, then shut down the server and then run it for the second time, I think the connection will be broken and you have to re-initialize it.
The isConnected() method will give you a false result, because this will always return true if the socket is not closed explicitly by you at the client side.
If you want to be sure, you can run your client-server connection once, then shut down the server, restart it and then try reading/writing from/to the server. If the connection is broken, you'll get -1 as a result from reading and an IOExceptionfrom writing.
Related
I'm implement a http server with version1.1 using java socket programming. I use a version 1.0 sample code and I want add the persistent connection feature by not closing socket utilt a "Connection : close" send to the server. However, I came accross with "java.net.SocketTimeoutException: Read timed out" info after an input like"localhost:8080/xxxx" on my browser and not receiving anything when tested with a client program. Code is too long, and I mention the matter parts bellow! Can you find the problems for me, thanks!!!
////////here is the server part using thread pool techs
//Webserver class
protected static Properties props = new Properties();
/* Where worker threads stand idle */
static Vector threads = new Vector();
public static void main(String[] a) throws Exception {
int port = 8080;
if (a.length > 0) {
port = Integer.parseInt(a[0]);
}
loadProps();
printProps();
/* start worker threads */
for (int i = 0; i < workers; ++i) {
Worker w = new Worker();
(new Thread(w, "worker #"+i)).start();
threads.addElement(w);
}
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket s = ss.accept();
Worker w = null;
synchronized (threads) {
if (threads.isEmpty()) {
Worker ws = new Worker();
ws.setSocket(s);
(new Thread(ws, "additional worker")).start();
} else {
w = (Worker) threads.elementAt(0);
threads.removeElementAt(0);
w.setSocket(s);
}
}
}
}
//Worker class inherit from Webserver class
byte[] buf;
Worker() {
buf = new byte[BUF_SIZE];
s = null;
}
synchronized void setSocket(Socket s) {
this.s = s;
notify();
}
public synchronized void run() {
while(true) {
if (s == null) {
/* nothing to do */
try {
wait();
} catch (InterruptedException e) {
/* should not happen */
continue;
}
}
try {
handleClient();
} catch (Exception e) {
e.printStackTrace();
}
/* go back in wait queue if there's fewer
* than numHandler connections.
*/
if(!headAttri.getPersistConnec())
s = null;
//
Vector pool = WebServer.threads;
synchronized (pool) {
if (pool.size() >= WebServer.workers) {
/* too many threads, exit this one */
try{
if(s != null)
s.close();
}catch (IOException e) {
e.printStackTrace();
}
return;
} else {
if(!headAttri.getPersistConnec())
pool.addElement(this);
}
}
}
}
//in handle client I mention the socket handles here(s is the socket)
void handleClient() throws IOException {
//...
s.setSoTimeout(WebServer.timeout);
s.setTcpNoDelay(true);
//...
try{
//...handle request and response the client
//...
}finally{
//close socket if head info "Connection: close" is found
if(headAttri.getPersistConnec()){
s.setKeepAlive(true);
}
else{
s.close();
}
}
}
//////////end server part
//////here is the client part
public SimpleSocketClient()
{
String testServerName = "localhost";
int port = 8080;
try
{
// open a socket
Socket socket = openSocket(testServerName, port);
// write-to, and read-from the socket.
// in this case just write a simple command to a web server.
String result = writeToAndReadFromSocket(socket, request_str[1]);
// print out the result we got back from the server
System.out.println(result);
// close the socket, and we're done
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private Socket openSocket(String server, int port) throws Exception
{
Socket socket;
// create a socket with a timeout
try
{
InetAddress inteAddress = InetAddress.getByName(server);
SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);
// create a socket
socket = new Socket();
// this method will block no more than timeout ms.
int timeoutInMs = 10*1000; // 10 seconds
socket.connect(socketAddress, timeoutInMs);
return socket;
}
catch (SocketTimeoutException ste)
{
System.err.println("Timed out waiting for the socket.");
ste.printStackTrace();
throw ste;
}
}
private String writeToAndReadFromSocket(Socket socket, String writeTo) throws Exception
{
try
{
// write text to the socket
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(writeTo);
bufferedWriter.flush();
//test
//bufferedWriter.write("GET src/WebServer.java HTTP/1.1\r\nHost: localhost\r\nConnection: close");
//bufferedWriter.flush();
// read text from the socket
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
//string handling code
String str;
while ((str = bufferedReader.readLine()) != null)
{
sb.append(str + "\n");
}
// close the reader, and return the results as a String
bufferedReader.close();
return sb.toString();
}
catch (IOException e)
{
e.printStackTrace();
throw e;
}
}
////end client part
//close socket if head info "Connection: close" is found
if(headAttri.getPersistConnec()){
s.setKeepAlive(true);
It is hard to tell from your code what you are really doing but based on this code fragment it looks like you are mixing up HTTP keep alive (i.e. Connection: keep-alive handling, multiple requests in a single TCP connection) with TCP keep alive (detect broken TCP connection). See Relation between HTTP Keep Alive duration and TCP timeout duration and HTTP Keep Alive and TCP keep alive for explanations about the difference.
I want add the persistent connection feature by not closing socket utilt a "Connection : close" send to the server
That's not how you do it. You have to close the connection yourself, either
after a request with a Connection: close header is received and you've sent the response, or
when you get a read timeout on the socket reading the next request.
The length of the read timeout is entirely up to you, because it is up to you to protect yourself from DOS attacks among other things.
NB calling Socket.setKeepAlive(true) has absolutely nothing whatsoever to do with it.
NB 2 You should look into java.util.concurrent.Executor rather than implement your own thread pool.
I will post my code below, a little background.
I am trying to connect to a gameserver on port 9339. my local port changes each time. The aim is to pass the packets through the proxy and display the info in the command line.
The client connects to the remote host using bluestacks which is running the game.
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 {
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) {
}
}
}
}
}
Basically the last thing that is printed out is "Starting proxy for gamea.clashofclans.com:9339 on port (whatever it chose).
Hopefully someone can help me.
I have this problem too, I don`t have enough time to correct this but i think using thread is that is why all mistake.
check your proxy for working on browser setting( May be proxy had problem)
If not,
I suggest to don`t use thread. maybe mutual exclusion occurs.
Your code is correct.It is working fine so you don't need any fix. What is happening is , your serverSocket in your proxy class is waiting for client to connect. that's why it is not going forward. What you need to do is, create a client and connect to it.
follow the step :
run your proxy.
then run your client
for the client, you can use this code,
public static void main(String[] args) throws IOException {
try {
int remoteport = 9339;
String host="127.0.0.1";
makeConnection(host, remoteport);
System.out.println("connection successful!");
} catch (Exception e) {
System.err.println(e);
}
}
public static void makeConnection(String host, int remoteport) throws IOException {
while (true) {
Socket client = null;
try {
client = new Socket(host, remoteport);
System.out.println("Client connected to server.");
break;
} catch (IOException e) {
System.err.println(e);
} finally {
if (client != null)
client.close();
if (client != null)
client.close();
}
}
}
I want to connect to a remote server from thread and keep sending strings. If the connection gets refused the thread should keep polling the port until the server is up again. How can I handle this exception and keep my thread fro crashing? The server may not be up for long time but thread should run indefinitely.
public void SendMessage(String message){
try {
socket = new Socket(actuatorAddress, destPort.get());
outToServer = socket.getOutputStream();
out = new DataOutputStream(outToServer);
out.flush();
out.write(message.getBytes());
} catch (IOException ex) {
System.out.println(ex.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
I changed some part of the code as below. For first time called Connect function and then subsequently called Send Message function through thread. The delay added to reconnecting helped reduce time lag recurred due to connecting to non existing server. Still think that there might be a better solution to the basic problem.
public boolean ConnectToActuator() {
try {
if(actuatorAddress.isReachable(2000)){
socket = new Socket();
socket.setPerformancePreferences(1, 2, 0);
socket.setTcpNoDelay(false);
socket.setSendBufferSize(32);
socket.connect(new InetSocketAddress(actuatorAddress, destPort.get()));
outToServer = socket.getOutputStream();
out = new DataOutputStream(outToServer);
connected = true;
disconnectedTimeout = 0;
}
}catch (ConnectException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}catch (IOException ex) {
connected = false;
System.out.println(ex.getMessage());
}
return connected;
}
public boolean SendToActuator(String message) {
if(connected == false){ //socket.isOutputShutdown()
disconnectedTimeout++;
if(disconnectedTimeout>20){
disconnectedTimeout = 0;
ConnectToActuator();
} else {
return connected;
}
}
try {
out.flush();
out.writeBytes(message);
disconnectedTimeout = 0;
connected = true;
} catch (UnknownHostException uhe) {
connected = false;
System.out.println(uhe.getMessage());
} catch (IOException ioe) {
connected = false;
System.out.println(ioe.getMessage());
}
return connected;
}
Given the following constraints in the comments:
Try to send the message to one of the 10 servers.
If none of the servers are available to receive the message, discard the message.
What you actually want to do is:
Iterate through a list of server addresses
Attempt to send a message to each of them
Break out of the loop right away if successful
Catch any errors on connection failure and try the next server
Here's an example class that will run through that scenario.
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MessageSender {
private static final Integer destPort = 1234;
private static final String[] serverAddresses = {
"address1",
"address2",
"address3" // Etc....
};
public Boolean SendMessage(String message) {
Boolean messageSentSuccessfully = false;
for (String addy : serverAddresses) {
messageSentSuccessfully = SendMessageToServer(addy, message);
if (messageSentSuccessfully) {
break;
}
}
return messageSentSuccessfully;
}
private Boolean SendMessageToServer(String serverAddress, String message) {
Boolean messageSent = false;
try {
Socket dataSocket = new Socket(serverAddress, destPort);
OutputStream outToServer = dataSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.write(message.getBytes());
out.flush();
messageSent = true;
} catch (Exception e) {
System.out.println(e);
}
return messageSent;
}
}
Hope that helps.
Pseudo:
while(true){
if(connect()) DoClientConnectedStuff();
sleep(reconnectTimeout);
};
please try below changes. if your connection refuses it will wait for 2s(2000ms) and then again try to connect with server. if connection being successful it will take outputstream, write data in a while loop and flush the data.
public void createSocketConnection() throws IOException
{
socket = new Socket(actuatorAddress, destPort.get());
if(socket!=null)
{
outToServer = socket.getOutputStream();
out = new DataOutputStream(outToServer);
}
}
public void SendMessage(String message){
boolean isRunning=false;
try
{
createSocketConnection();
isRunning=true;
while(isRunning)
{
out.write(message.getBytes());
out.flush();
}
} catch (java.net.ConnectException conExcp) {
System.out.println(ex.getMessage());
try{
Thread.sleep(2000);
}catch(Exception ee){}
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
Context:
The following AsyncTask for an android application sends and receives so called Request objects from a server.
If the user makes changes to his stuff in the app, new request objects get generated and added to the synchronization queue. If he then hits the sync-button the AsyncTask is created and executed with his requests as parameters.
The handler finally takes all answers and sets the neccessary consequences in the database. He then finally updates the UI by calling one single method on the UI thread (onPostExecute).
public class RequestSender extends AsyncTask<Request, Void, Boolean>{
// Server data
private String host;
private int port = 1337;
private Socket socket;
private AnswerHandler handler;
public RequestSender(AnswerHandler handler) {
this.host = "hostNameHere";
this.handler = handler;
}
/**
* This method gets started as asynchronous task when you call .run()
* #return
*/
#Override
protected Boolean doInBackground(Request... requests) {
return sendAndReceive(requests);
}
private boolean sendAndReceive(Request... requests) {
boolean isConnected = this.initSocket();
if(isConnected) {
this.send(requests);
this.waitForAnswer();
} else {
handler.setRequests(requests);
}
return isConnected;
}
/**
* Tries to open a socket on the android device to a specified Host
*/
private boolean initSocket() {
try {
SocketAddress sockaddr = new InetSocketAddress(host, port);
socket = new Socket();
socket.connect(sockaddr, 5000);
return true;
} catch (UnknownHostException e) {
System.err.println("Unknown Host in initSocket()");
} catch (IOException e) {
System.err.println("Connection timed out");
}
return false;
}
/**
* Tries to send a request to the server
* #param request
*/
public void send(Request... request) {
if(socket != null) {
try {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(request);
out.flush();
} catch (IOException e) {
System.err.println("Couldn't write to socket in RequestSender");
}
}
}
/**
* Waits for the answer from the server and reports the result in the handler
*/
private void waitForAnswer() {
try {
socket.setSoTimeout(5000);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Request[] answers = (Request[]) in.readObject();
socket.close();
handler.setRequests(answers);
} catch (StreamCorruptedException e) {
System.err.println("Failed to open stream from server");
} catch (IOException e) {
System.err.println("Failed to read answers from server");
} catch (ClassNotFoundException e) {
System.err.println("Failed to read class from server");
}
}
#Override
protected void onPostExecute(Boolean a) {
handler.updateUI();
}
}
Now my Problem:
The whole thing works without any problem for a few times (It depends on the goodwill of my phone how many times), but then it seems like the task gets stuck somewhere without giving me any error message on System.err.
Restarting the app solves the problem and it works again without any problem.
I already read that AsyncTasks get executed on one single thread since Honeycomb. I set a timeout on open socket and read in, so a stuck task should terminate after this timeout.
Is there any problem with my code and could you imagine a solution for this?
Recently I face this problem and after debugging a lot and brain storming for a week I finally got the bug.
Ok lets do some homework.
Process to send/receive data
Establish a connection. Let assume connectToServer() is a function that physically connects the device to the server.
The socket/TCP part. In your case you have doInbackground(), in which you are calling initSocket() to initiate a socket connetion.
In real world scenario when you request a connection to a server it takes some time, may be a one or two seconds. So you should wait for that time before initiating a socket connection request. If a socket request send before a connection then it goes to lock state and releases after the default time out is finished which make it stuck.
Programming scenario
connectToServer();
// wait for 1 or 2 second.
initSocket();
Sample code
/* Function to check whether we are physically connected to the server or not */
private boolean isConnEstablished(){
WifiInfo connInfo = mManager.getConnectionInfo();
return mManager.isWifiEnabled() && connInfo.getNetworkId() != -1 && connInfo.getIpAddress() != 0;
}
private void initSocket() {
boolean scanning = true;
int tryCount = 5; // we trying for 5 times
try {
while (scanning && tryCount > 0) {
try {
if (isConnEstablished()) {
try{
Thread.sleep(500);
}catch (InterruptedException e){
Log.e("Yo", "sleep-error");
}
tConnection = new Socket(host, port);
scanning = false;
Log.e(getClass().getName(), "Socket connection established");
}else {
throw new ConnectException();
}
} catch (ConnectException e) {
Log.e(getClass().getName(), "connecting again...");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Log.e(getClass().getName(), "System sleep-error: " + ex.getMessage());
}
}
tryCount--;
}
}
I'm conducting an experiment to see how long it takes the TCP in java. First I start the server. Then call the function client_tcp many times, more than 50000 times. And measure the time it takes to connect, and send and receive 1 byte. When the server get more than 16384 requests (sometimes varies), the client can't connect to the server.
I don't know if it is because of the receive buffer size in the server socket. In my case, ss.getReceiveBufferSize() = 131072.
Here is the code:
public synchronized void server_tcp(int port) {
ServerSocket ss;
Socket so;
InputStream is;
OutputStream os;
try {
ss = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Unable to connect to port " + port +
" TCP socket.");
return;
}
while (true) {
try {
so = ss.accept();
is = so.getInputStream();
os = so.getOutputStream();
int ch = is.read();
os.write(65);
so.close();
} catch (IOException e) {
System.out.println("Something went wrong.");
} catch (InterruptedException e) {
System.out.println("Bye.");
}
}
}
public void client_tcp(String host, int port) {
Socket so = null;
InputStream is = null;
OutputStream os = null;
try {
so = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println("Error Host not found.");
return;
} catch (IOException e) {
Syste.err.println("Error Creating socket.");
return;
}
try {
os = so.getOutputStream();
is = so.getInputStream();
os.write(65);
is.read();
os.close();
is.close();
so.close();
} catch (IOException e) {
System.err.println("Error.");
return;
}
}
What's wrong?
Thank you.
You are creating a massive number of sockets almost at once and the OS is not having time enough to release them. You could add a tiny delay (to be experimentally tuned) to the loop that invokes the client_tcp() method.
for(int i=0; i<50000; i++) {
new SocketReuse().client_tcp("127.0.0.1", 4444);
Thread.sleep(2); // 2 milliseconds delay
}