I'm experiencing some issues with this code depending on the browser I use, there are URL's displayed correctly in IE but being displayed as plain text in Firefox (for instance www.microsoft.es looks good on IE but not on Firefox).
Don't know what I'm doing wrong here, I think that there's a problem with the headers that I'm using but I'm not sure...
This is the code:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Server {
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
#SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedOutputStream out = new BufferedOutputStream(clientSocket.getOutputStream());
String url = null;
int i=0;
String [] headers = new String [100];
String buffer;
while ((buffer = in.readLine()) != null) {
headers[i]=buffer;
i++;
if(buffer.contains("GET"))
{
String[] splitText = buffer.split(" ");
url = splitText[1];
}
if(buffer.contains("POST"))
{
String[] splitText = buffer.split(" ");
url = splitText[1];
}
if(buffer.contains("CONNECT"))
{
String[] splitText = buffer.split(" ");
url = "https://"+splitText[1];
}
if (buffer.isEmpty()) break;
}
URL u = new URL(url);
URLConnection connection = u.openConnection();
for (int x=1;x<i-1;x++){
if (!headers[x].contains("Accept-Encoding:")){
connection.setRequestProperty(headers[x].substring(0, headers[x].indexOf(":")).toString() , headers[x].replace(headers[x].substring(0, headers[x].indexOf(":") +2), "").toString());
}
}
boolean redirect = false;
int status = ((HttpURLConnection) connection).getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
if (redirect) {
String Url = connection.getHeaderField("Location");
URL urlloc = new URL(Url);
connection = urlloc.openConnection();
for (int x=1;x<i-1;x++){
if (!headers[x].contains("Accept-Encoding:")){
connection.setRequestProperty(headers[x].substring(0, headers[x].indexOf(":")).toString() , headers[x].replace(headers[x].substring(0, headers[x].indexOf(":") +2), "").toString());
}
}
}
byte[] chunk = new byte[1024];
int bytesRead;
InputStream stream;
stream = connection.getInputStream();
while ((bytesRead = stream.read(chunk)) > 0) {
out.write(chunk, 0, bytesRead);
out.flush();
}
out.close();
in.close();
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Any help would be appreciated.
Thanks.
I'm not sure what the problem is, but you should use a tool like Wireshark to examine the actual network traffic between the browser and your proxy, and compare it to the network traffic between the browser and the site when you connect to the site directly.
Related
I want to develop a HTTP Proxy ,
The code is here ;
When I run my code , I get this exception :
Started on: 9999
request for : /setwindowsagentaddr
Encountered exception: java.net.MalformedURLException: no protocol: /setwindowsagentaddr
package proxy;
import java.net.*;
import java.io.*;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listenning = true;
// String host="192.168.1.10";
int port = 9999;
try{
port = Integer.parseInt(args[0]);
}catch(Exception e){
}
try{
serverSocket = new ServerSocket(port);
System.out.println("Started on: " + port);
}catch(Exception e){
// System.err.println("Could not listen on port: " + args[0]);
System.exit(0);
}
while(listenning){
new ProxyThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
and the ProxyThread here :
public class ProxyThread extends Thread {
private Socket socket = null;
private static final int BUFFER_SIZE = 32768;
public ProxyThread(Socket socket){
super("Proxy Thread");
this.socket=socket;
}
public void run(){
try {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine , outputLine;
int cnt = 0 ;
String urlToCall="";
//get request from client
// socket.getPort();
while((inputLine=in.readLine()) != null){
try{
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
}catch(Exception e){
break;
}
///parse the first line of the request to get url
if(cnt==0){
String [] tokens = inputLine.split(" ");
urlToCall = tokens[1];
System.out.println("request for : "+ urlToCall);
}
cnt++;
}
BufferedReader rd = null;
try{
//System.out.println("sending request
//to real server for url: "
// + urlToCall);
///////////////////////////////////
//begin send request to server, get response from server
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
//not doing http post
conn.setDoOutput(false);
System.out.println("Type is : "+ conn.getContentType());
System.out.println("length is : "+ conn.getContentLength());
System.out.println("allow user interaction :"+ conn.getAllowUserInteraction());
System.out.println("content encoding : "+ conn.getContentEncoding());
System.out.println("type is : "+conn.getContentType());
// Get the response
InputStream is = null;
HttpURLConnection huc = (HttpURLConnection) conn;
if (conn.getContentLength() > 0) {
try {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
} catch (IOException ioe) {
System.out.println(
"********* IO EXCEPTION **********: " + ioe);
}
}
//end send request to server, get response from server
//begin send response to client
byte [] by = new byte[BUFFER_SIZE];
int index = is.read(by,0,BUFFER_SIZE);
while ( index != -1 )
{
out.write( by, 0, index );
index = is.read( by, 0, BUFFER_SIZE );
}
out.flush();
//end send response to client
}catch(Exception e){
//can redirect this to error log
System.err.println("Encountered exception: " + e);
//encountered error - just send nothing back, so
//processing can continue
out.writeBytes("");
}
//close out all resources
if (rd != null) {
rd.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
How can I fix this exceptions?
So the error isn't lying, /setwindowsagentaddr isn't a valid url. How would it know what protocol to use?
Try using something like http://localhost:8080/setwindowsagentaddr
This is the class containing the main() method:
public class MultithreadedProxyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
int port = 10000; //default
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
//ignore me
System.out.println("gnore");
}
try {
serverSocket = new ServerSocket(port);
System.out.println("Started on: " + port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + args[0]);
System.exit(-1);
}
while (listening) {
new ProxyThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
And this is the ProxyThread class:
public class ProxyThread extends Thread {
private Socket socket = null;
private static final int BUFFER_SIZE = 32768;
public ProxyThread(Socket socket) {
super("ProxyThread");
this.socket = socket; //initialzed my parent before you initalize me
}
public void run() {
//get input from user
//send request to server
//get response from server
//send response to user
System.out.println("run");
try {
DataOutputStream out =
new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
int cnt = 0;
String urlToCall = "";
///////////////////////////////////
//begin get request from client
while ((inputLine = in.readLine()) != null) {
try {
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
} catch (Exception e) {
System.out.println("break");
break;
}
//parse the first line of the request to find the url
if (cnt == 0) {
String[] tokens = inputLine.split(" ");
urlToCall = tokens[1];
//can redirect this to output log
System.out.println("Request for : " + urlToCall);
}
cnt++;
}
//end get request from client
///////////////////////////////////
BufferedReader rd = null;
try {
//System.out.println("sending request
//to real server for url: "
// + urlToCall);
///////////////////////////////////
//begin send request to server, get response from server
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
//not doing HTTP posts
conn.setDoOutput(false);
//System.out.println("Type is: "
//+ conn.getContentType());
//System.out.println("content length: "
//+ conn.getContentLength());
//System.out.println("allowed user interaction: "
//+ conn.getAllowUserInteraction());
//System.out.println("content encoding: "
//+ conn.getContentEncoding());
//System.out.println("content type: "
//+ conn.getContentType());
// Get the response
InputStream is = null;
HttpURLConnection huc = (HttpURLConnection)conn;
if (conn.getContentLength() > 0) {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
}
//end send request to server, get response from server
///////////////////////////////////
///////////////////////////////////
//begin send response to client
byte by[] = new byte[ BUFFER_SIZE ];
int index = is.read( by, 0, BUFFER_SIZE );
while ( index != -1 )
{
out.write( by, 0, index );
index = is.read( by, 0, BUFFER_SIZE );
}
out.flush();
//end send response to client
///////////////////////////////////
} catch (Exception e) {
//can redirect this to error log
System.err.println("Encountered exception: " + e);
//encountered error - just send nothing back, so
//processing can continue
out.writeBytes("");
}
//close out all resources
if (rd != null) {
rd.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have copy-pasted the above code from the internet, however I am having difficulties running it.
To answer the question from the post title, the run() method from ProxyThread class is called by JVM, after the thread has been started new ProxyThread(serverSocket.accept()).start(); and it usually contains the actual work that a thread should performed (in this case, it handles whatever the server socket receives and it accepts a connection from a client).
The moment when JVM calls run() method cannot be controlled by the programmer, but is after the thread has been started.
run() method is never called explicitly by the programmer.
I think the problem is that client 2 is not entering receiving mode and the connection between clients closes before first client sends something to the second... but I might be wrong.
Here is the code of server and clients. Program is based on token ring algorithm. I'm not fluent in Java so I suppose I didn't use the best way to solve it.
Server:
public class TokenServer
{
ServerSocket clientConn;
public TokenServer(int port){
System.out.println("Server connecting to port "+port);
try {
clientConn = new ServerSocket(port);
}
catch (Exception e) {
System.out.println("Exception:"+e);
System.exit(1);
}
}
public static void main(String[] args) {
int port = 8000;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
port = 8000;
}
}
TokenServer server = new TokenServer(port);
System.out.println("Server running on port "+port);
server.listen();
}
public void listen(){
try{
System.out.println("Waiting for clients...");
while(true) {
Socket clientReq = clientConn.accept();
System.out.println("Connection from "+clientReq.getInetAddress().getHostName());
serviceClient(clientReq);
}
}
catch (IOException e) {
System.out.println("Exception:"+e);
}
}
public void serviceClient(Socket s){
System.out.println("New request from "+s.getInetAddress());
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
int message_id;
Object message = null;
try{
outStream = new ObjectOutputStream(s.getOutputStream());
inStream = new ObjectInputStream(s.getInputStream());
message_id = inStream.readInt();
System.out.println("Got message "+message_id);
int zmienna;
zmienna = message_id + message_id;
outStream.writeObject(zmienna);
outStream.flush();
}
catch (Exception e) {
System.out.println("Exception:"+e);
}
System.out.println("Done.");
}
}
Client 1:
public class TokenClient1{
int sendport,recport;
boolean hasToken = true;
boolean setSendData = false;
String host;
public TokenClient1(String host){
this.host = host;
}
void setSendPort(int sendport)
{
this.sendport = sendport;
}
void setRecPort(int recport)
{
this.recport = recport;
}
public Object sendMessage(int message_id) throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Object response = null;
serverConn = new Socket(host, sendport);
outStream = new ObjectOutputStream(serverConn.getOutputStream());
inStream = new ObjectInputStream(serverConn.getInputStream());
outStream.writeInt(message_id);
outStream.flush();
response = inStream.readObject();
serverConn.close();
//hasToken = false;
return response;
}
public Object recData() throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
Object response = null;
serverConn = new Socket(host, recport);
inStream = new ObjectInputStream(serverConn.getInputStream());
response = inStream.readObject();
serverConn.close();
if(response.toString().equals("Token"))
{
hasToken = true;
}
return response;
}
public static void main (String[] args){
TokenClient1 client = new TokenClient1("localhost");
TokenClient1 server = new TokenClient1("localhost");
client.setSendPort(8002);
client.setRecPort(8002);
server.setSendPort(8000);
Scanner scan = new Scanner(System.in);
int wybor, zmienna;
try{
while(true)
{
if(client.hasToken == true){
System.out.println("Do you want to enter the Data --> \n1. YES \n0. NO");
wybor = scan.nextInt();
switch (wybor) {
case 1:
{
System.out.println("ready to send \n Podaj liczbe do dodania: ");
//server.setSendData = true;
zmienna = scan.nextInt();
System.out.println("odpowiedz servera:");
System.out.println((Integer)server.sendMessage(zmienna));
break;
}
case 0:
{
System.out.println("i m in else");
client.sendMessage(0);
client.recData();
System.out.println("i m leaving else");
break;
}
}
}
else {
System.out.println("ENTERING RECEIVING MODE...");
client.recData();
}
}
}
catch(Exception e) {
System.out.println("Esception:"+e);
}
}
}
Client 2:
public class TokenClient2
{
int sendport,recport;
boolean hasToken = false;
String host;
ServerSocket clientConn;
public TokenClient2(String host){
this.host = host;
}
void setSendPort(int sendport)
{
this.sendport = sendport;
}
void setRecPort(int recport)
{
this.recport = recport;
}
public Object sendMessage(int message_id) throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Object response = null;
serverConn = new Socket(host, sendport);
outStream = new ObjectOutputStream(serverConn.getOutputStream());
inStream = new ObjectInputStream(serverConn.getInputStream());
outStream.writeInt(message_id);
outStream.flush();
response = inStream.readObject();
serverConn.close();
//hasToken = false;
return response;
}
void recData() throws Exception
{
try{
System.out.println("Waiting for clients...");
// while(true) {
Socket serverConn;
ObjectInputStream inStream = null;
Object response = null;
clientConn = new ServerSocket(8002);
serverConn = new Socket(host, 8000);
Socket clientReq = clientConn.accept();
System.out.println("Connection from "+clientReq.getInetAddress().getHostName());
inStream = new ObjectInputStream(serverConn.getInputStream());
response = inStream.readObject();
clientConn.close();
System.out.println("Waiting for cents...");
if(response.equals(0))
{
System.out.println("tdfss...");
hasToken = true;
}
//return response;
}
//}
catch (IOException e) {
System.out.println("Exception:"+e);
}
}
public static void main (String[] args){
TokenClient2 client = new TokenClient2("localhost");
TokenClient2 server = new TokenClient2("localhost");
client.setSendPort(8002);
client.setRecPort(8002);
server.setSendPort(8000);
Scanner scan = new Scanner(System.in);
int wybor, zmienna;
try{
while(true)
{
if(client.hasToken == true){
System.out.println("Do you want to enter the Data --> \n1. YES \n0. NO");
wybor = scan.nextInt();
switch (wybor) {
case 1:
{
System.out.println("ready to send \n Podaj liczbe do dodania: ");
//server.setSendData = true;
zmienna = scan.nextInt();
System.out.println("odpowiedz servera:");
System.out.println((Integer)server.sendMessage(zmienna));
break;
}
case 0:
{
System.out.println("i m in else");
client.sendMessage(0);
client.recData();
System.out.println("i m leaving else");
break;
}
}
}
else {
client.hasToken=true;
System.out.println("ENTERING RECEIVING MODE...");
client.recData();
}
}
}
catch(Exception e) {
System.out.println("Esception:"+e);
}
}
}
I'm writing a proxy server using sockets, now it seems that it's "working" more or less but the problem I'm experiencing now is that the images of the URL's are not getting back to the browser, only the text is returned...
This is the code:
//create inputstream to receive the web page from the host
BufferedInputStream inn = new BufferedInputStream(clientURLSocket.getInputStream());
//create outputstream to send the web page to the client
BufferedOutputStream outt = new BufferedOutputStream(clientSocket.getOutputStream());
URL u = new URL("http://"+url);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[1024];
int bytesRead;
InputStream stream = u.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
outt.write(outputStream.toByteArray());
outt.flush();
Maybe ByteArrayOutputStream is not good to receive images?
Edit (sorry for the late response):
This is my new code:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Server {
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
#SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket clientSocket = serverSocket.accept();
Socket clientURLSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
clientProcessingPool.submit(new ClientTask(clientURLSocket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private Socket clientSocket;
private Socket clientURLSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
this.clientURLSocket = clientSocket;
}
#Override
public void run() {
try {
String url = null;
String curl = null;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String buffer;
while ((buffer = in.readLine()) != null) {
//System.out.println(buffer);
if(buffer.contains("GET"))
{
String[] splitText = buffer.split(" ");
curl = splitText[1];
System.out.println(curl);
}
if(buffer.contains("Host"))
{
//parse the host
url = buffer.replace("Host: ", "");
System.out.println(url);
}
if (buffer.isEmpty()) break;
}
//String IP = InetAddress.getByName(url).getHostAddress().toString();
//new socket to send the information over
clientURLSocket = new Socket(url, 80);
//get data from a URL
/* URL host = new URL("http://"+url);
URLConnection urlConnection = host.openConnection();
InputStream input = urlConnection.getInputStream();
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
input.close();*/
//create inputstream to receive the web page from the host
BufferedInputStream inn = new BufferedInputStream(clientURLSocket.getInputStream());
//create outputstream to send the web page to the client
BufferedOutputStream outt = new BufferedOutputStream(clientSocket.getOutputStream());
URL u = new URL(curl);
HttpURLConnection connection = null;
connection = (HttpURLConnection) u.openConnection();
connection.connect();
//ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[1024];
int bytesRead;
InputStream stream = connection.getInputStream();
while ((bytesRead = stream.read(chunk)) > 0) {
//outputStream.write(chunk, 0, bytesRead);
outt.write(chunk, 0, bytesRead);
outt.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
//outt.write(outputStream.toByteArray());
//outt.flush();
outt.close();
inn.close();
clientURLSocket.close();
/*
out.close();
in.close();
clientSocket.close();
*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now the problem is that google.com is working fine (it shows all the images and text), but for example youtube.com is not working fine (it also shows the text and images but the web is not being showed completely and it's disordered).
What I'm missing in this code?
By the way, thanks EJP & JB Nizet for your help!
It seems you don't understand how HTTP and HTML work.
When you go to http://google.com with your browser, a first request is sent to get the HTML page. The server response contains the HTML markup, and only that. Then the browser reads and parses this HTML markup and sees that it contains (for example)
<img src="logo.png"/>
So it sends a new HTTP request to the URL http://google.com/logo.png. The server sends a response containing the bytes of the logo image.
If your code only sends a single request to http://google.com, you'll never get the logo.
An HTTP proxy is a lot simpler than what you're doing here.
You are supposed to connect to the URL named in the CONNECT command. Not parse the GET and HOST headers. Once you've processed the CONNECT command, the rest is just copying bytes back and forth.
I, doing some computer network homework and I have to develop some sort of distributed DBMS which are connected to each other with peer to peer network, so I have a TCP client and a TCP server in one .java file which running next to each other by threads. the TCP Server of the class always listen to the other TCP client from others and give them service, the problem is when I System.out the String which I have to send back to the client on the Server side it's in the way which it's supposed to be but after sending , the client gets nothing and prints null. I wrote my code based on tutorials I found on the net and I when I test them they worked well but it's not working in my own code. could you see where my problem is? thanks
class CommandComp
{
int PORT = 1210;
int PORT2 = 1211;
String IPLocal = "";
String IPdest = "";
InetAddress IPAD;
InetAddress IPAD2;
int numOfNodes;
int numOfNodesnonchanged;
String[] Nodes;
Random rand = new Random();
int max = 2000;
int min = 1000;
String command;
Socket clientSocket;
CommandComp(String[] IPdest, String IPLocal, int numOfNodes, String command)
{
try
{
this.numOfNodes = numOfNodes;
numOfNodesnonchanged = numOfNodes;
this.IPLocal = IPLocal;
this.Nodes = IPdest;
this.command = command;
// this.IPAD = InetAddress.getByName(this.IPdest);
this.IPAD2 = InetAddress.getByName(this.IPLocal);
// clientSocket = new Socket(this.IPAD , PORT ,this.IPAD2 , PORT2 );
}
catch (Exception e)
{
// //e.printStackTrace();
}
}
public String call()
{
int i = 0;
while (numOfNodes > 0)
{
String response = "";
try
{
Thread.sleep(rand.nextInt(max - min + 1) + min);
i = numOfNodes - 1;
int max2 = 50;
int min2 = 10;
this.IPAD = InetAddress.getByName(Nodes[i]);
clientSocket = new Socket(this.IPAD, PORT, this.IPAD2, PORT2 + rand.nextInt(max2 - min2 + 1) + min2);
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.println(command);
System.out.println(inFromServer.readLine());
response = inFromServer.readLine();
outToServer.close();
inFromServer.close();
clientSocket.close();
numOfNodes--;
System.out.println(Nodes[i] + " Remote DBMS");
System.out.println(response);
}
catch (Exception e)
{
e.printStackTrace();
try
{
clientSocket.close();
}
catch (Exception e2)
{
// TODO: handle exception
}
}
}
return command;
}
}
class TCPListnerService
implements Callable<Object>
{
String from;
String to;
ServerSocket Server;
String IP = "";
int numOfNodes;
int numofNodesUnchanged;
static clientThread t[];
TCPListnerService(String IP, int numOfNodes)
{
try
{
this.IP = IP;
this.numOfNodes = numOfNodes;
numofNodesUnchanged = numOfNodes * 2;
this.t = new clientThread[numofNodesUnchanged];
InetAddress IPAD = InetAddress.getByName(IP);
Server = new ServerSocket(1210, 20, IPAD);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String call()
throws Exception
{
String gotten = "";
while (numOfNodes > 0)
{
Socket connected = Server.accept();
for (int i = 0; i < numofNodesUnchanged; i++)
{
if (t[i] == null)
{
(t[i] = new clientThread(connected)).start();
break;
}
}
}
return gotten;
}
}
class clientThread
extends Thread
{
Socket clientSocket = null;
sqlite DB = new sqlite();
String response = "";
String fromclient;
String delims = "[ =)(',\n\t\r]+";
String[] tokens;
public clientThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
public void run()
{
try
{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(clientSocket.getOutputStream(), true);
fromclient = inFromClient.readLine();
tokens = fromclient.split(delims);
if (tokens[0].equalsIgnoreCase("create")
|| tokens[0].equalsIgnoreCase("drop")
|| tokens[0].equalsIgnoreCase("delete")
|| tokens[0].equalsIgnoreCase("insert")
|| tokens[0].equalsIgnoreCase("update")
|| tokens[0].equalsIgnoreCase("select"))
{
response = DB.RunQuery(fromclient);
System.out.println(response);
outToClient.print(response);
clientS.close();
}
else if (tokens[0].equalsIgnoreCase("shut"))
{
System.exit(0);
}
inFromClient.close();
outToClient.close();
clientSocket.close();
}
catch (Exception e)
{
}
;
}
}
The problem is here:
inFromClient.close();
outToClient.close();
clientSocket.close();
You are closing (1) the input stream, which closes the socket, (2) the PrintWriter, which flushes it and closes the socket, and (3) the socket. Obviously (2) cannot succeed if the socket is already closed. The data you sent to the client is still buffered, never got flushed, so it never got sent.
Just close the PrintWriter, and close the socket in a finally block in case (2) fails somehow. No need to close the input at all.