Simple Java proxy server - google search error - java

I've written simple HTTP proxy server everything works except google search, Im reciving "net::ERR_EMPTY_RESPONSE" error in google chrome, and "Connection closed by remote server" in Opera. I don't have anymore ideas how to solve it. Could you help me?
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Server <Parametr>{
private Calendar current;
private DateFormat dformat;
private int localport = 0;
private int remoteport = 80;
private String remoteAddress = "127.0.0.1";
private Proxy proxy;
private ServerSocketChannel servsocketchannel;
private boolean local = false;
public Server(int port){
setServerPort(port);
openServerPort();
checkAndSetRemoteProxyServer();
dformat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
current = Calendar.getInstance();
createServerSocketAndTalk();
}
public void setServerPort(int port){
this.localport = port;
}
public void setProxyAddressAndPort(int port, String address){
this.remoteport = port;
this.remoteAddress = address;
}
public void openServerPort(){
try {
servsocketchannel = ServerSocketChannel.open();
servsocketchannel.socket().bind(new java.net.InetSocketAddress(localport));
} catch (BindException exc) {
System.out.println("Server isn't started, local port is blocked or used, check firewall or set new port");
} catch (IOException e){
System.out.println("Server isn't started, local port is blocked or used, check firewall or set new port");
}
}
public void checkAndSetRemoteProxyServer(){
boolean ERROR = false;
Socket proxysocketchannel = null;
try {
proxysocketchannel = new Socket(remoteAddress, remoteport);
} catch (UnknownHostException ex) {
System.out.println("Proxy server address is probably offline, please provide new server address --- RUNNING LOCAL PROXY MODE");
ERROR = true;
} catch (IOException exc) {
System.out.println("Connecting to the proxy server failed, please review address and port --- RUNNING LOCAL PROXY MODE");
ERROR = true;
}
if(!ERROR){
System.out.println("Proxy state - online");
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(remoteAddress, remoteport));
System.out.println("Initialization successful - waiting for clients ");
}
else{
System.out.println("Problem with proxy connection, check your settings or set new proxy address --- RUNNING LOCAL PROXY MODE");
System.out.println("Proxy local mode initialization successful - waiting for clients ");
local = true;
}
}
public void createServerSocketAndTalk(){
try {
while(servsocketchannel.isOpen()){
Runnable r = new ClientHandler(servsocketchannel.accept());
Thread t = new Thread(r);
t.start();
}
}catch(NotYetBoundException exc){
System.out.println("Server not started local port is already used, please choose new local port");
}catch (AsynchronousCloseException ex) {
System.out.println("Server Closed");
}
catch (IOException e) {
e.printStackTrace();
}
}
class ClientHandler implements Runnable{
SocketChannel client = null;
private static final int BUFFER_SIZE = 32768;
public ClientHandler(SocketChannel client){
this.client = client;
}
#Override
public void run() {
letsTalk();
try {
this.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
public void letsTalk(){
while(true){
if(client.socket().isClosed()){
break;
}
BufferedReader clientin = null;
DataOutputStream clientout = null;
try {
clientin = new BufferedReader(new InputStreamReader(client.socket().getInputStream()));
clientout = new DataOutputStream(client.socket().getOutputStream());
} catch (IOException e) {
System.out.println("Error with client connection");
break;
}
String inputline;
String url = "";
try {
while((inputline = clientin.readLine()) != null){
System.out.println(inputline);
StringTokenizer readerclient = new StringTokenizer(inputline);
if(readerclient.nextToken().equals("GET")){
url = readerclient.nextToken();
System.out.println("Requested URL: " + url);
break;
}
if(readerclient.nextToken().equals("POST")){
System.out.println("POST");
}
}
} catch (IOException e) {
System.out.println("URL REQUEST ERROR");
e.printStackTrace();
} catch (NullPointerException exc){
}
try {
URL reqURL = new URL(url);
URLConnection connection = null;
if(local){
connection = reqURL.openConnection();
}
else {
connection = reqURL.openConnection(proxy);
}
connection.setDoInput(true);
connection.setDoOutput(false);
InputStream is = null;
is = connection.getInputStream();
byte by[] = new byte[ BUFFER_SIZE ];
int index = is.read( by, 0, BUFFER_SIZE );
while ( index != -1 ){
clientout.write( by, 0, index );
index = is.read( by, 0, BUFFER_SIZE );
}
clientout.flush();
}catch(Exception ex){
}
try {
clientin.close();
clientout.close();
// client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

I found the solution.
You have to add the following to URLConnection
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");

Related

How to Create a Backup Server in TCP Java Application,

I have a Java application that has a TCP Server and It handles the client requests. Now I want to create a TCP backup Server, so that when the TCP Server Fails, the backup server continues from the point the TCP Server failed and Handle the client request.
How this can be done?
I have a client and a server.
This is my code for TCP Server for now..
import java.net.*;
import java.io.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class TCPServer {
static ScriptEngineManager mgr;
static ScriptEngine engine;
public static void main(String args[]) {
mgr = new ScriptEngineManager();
engine = mgr.getEngineByName("js");
try {
int serverPort = 7896; // the server port
ServerSocket listenSocket = new ServerSocket(serverPort);
while (true) {
System.out.println("Server is ready and waiting for requests .... ");
Socket clientSocket = listenSocket.accept();
System.out.println("request received from client with IP : " + clientSocket.getInetAddress());
System.out.println("port of client : " + clientSocket.getPort());
Thread c = new Connection(clientSocket);
}
} catch (IOException e) {
//if already in use then redirect the request to backup server
System.out.println("Listen socket:" + e.getMessage());
}
}
}
class Connection extends Thread {
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
//send client request to bacckup server, with client IP adddress and port number
//BackupTCPServer bus = new BackupTCPServer();
//bus.clientIP = clientSocket.getInetAddress();
//bus.clientPort = clientSocket.getPort();
//System.out.println(bus);
try {
String s = in.readUTF();
//bus.Expressionsbackup.add(s);
String exp = "";
int res = 0;
while (s != null) {
TCPServer.engine.put("i", 2);
TCPServer.engine.put("j", 4);
exp =s;
Object result = TCPServer.engine.eval(exp);
double st = (Double)result;
out.writeUTF(Double.toString(st));
//bus.expressionevaluated++;
s = in.readUTF();
}
}
catch (ScriptException se) {
System.out.println("SE:" + se.getMessage());
}
catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (Exception e) {
/*close failed*/
}
}
}
}

Object not being received by server when checking for type of object sent by socket

I want to check what type of object is sent to the server as there are two types of clients sending object, one which is a Car Driver and another which is a pedestrian. But whenever I use the if(datain.readObject() instanceof Pedestrian or CarDriver) the server doesn't receive any object and no response is sent to the client anymore. Here is my code:
Server
package eece350;
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
/**
*
* #author user
*/
public class SkillsServer {
private ServerSocket serverSocket;
private void acceptConnections() {
try {
int port = 7171;
serverSocket = new ServerSocket(port);
}
catch (IOException e)
{
System.err.println("ServerSocket instantiation failure");
e.printStackTrace();
System.exit(0);
}
// Entering the infinite loop
while (true) {
try {
// wait for a TCP handshake initialization (arrival
of a "SYN"
// packet)
Socket newConnection = serverSocket.accept();
System.out.println("accepted connection");
// Now, pass the connection socket created above to a thread and
// run it in it
// First create the thread and pass the connection socket to it
// This is a non-blocking function: constructor of the class
// ServerThread
ServerThread st = new ServerThread(newConnection);
// Then, start the thread, and go back to waiting for another
// TCP connection
// This also is not blocking
new Thread(st).start();
}
catch (IOException ioe)
{
System.err.println("server accept failed");
}
}
}
public static void main(String[] args) throws NullPointerException,
ClassNotFoundException, FileNotFoundException, SQLException
{
SkillsServer server = null;
server= new SkillsServer();
// call this function, which will start it all...
server.acceptConnections();
}
// Internal class
class ServerThread implements Runnable
{
private Socket socket;
private ObjectInputStream datain;
private ObjectOutputStream dataout;
private DataOutputStream outToClient;
ServerThread(Socket socket)
{
// Inside the constructor: store the passed object in the data
// member
this.socket = socket;
}
public void run()
{
try
{
// Input and output streams, obtained from the member socket
// object
outToClient = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
datain = new ObjectInputStream(new
BufferedInputStream(socket.getInputStream()));
//dataout = new ObjectOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
}
catch (IOException e)
{
return;
}
String name="";
Coordinates location;
Coordinates Destination;
int numberofPassenger;
double chargingPerKilometer;
int carCapacity,did;
Regulations regulations;
boolean connectionActive = true;
String reply="";
while (connectionActive)
{
try
{
if(datain.readObject().getClass()==CarDriver.class)
{
String url
="jdbc:sqlserver://localhost:1433"+";databaseName=EECE350Project;Integrated
Security=True";
String userName = "Mahdi";
String password = "admin";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn =
DriverManager.getConnection(url,userName,password);
Statement stmt = conn.createStatement();
CarDriver CarDriver1 = (CarDriver)datain.readObject();
name=CarDriver1.getName();
location=CarDriver1.getLocation();
Destination=CarDriver1.getDestination();
numberofPassenger=CarDriver1.getNumofPassengers();
chargingPerKilometer=CarDriver1.getChargingPerKilometer();
carCapacity = CarDriver1.getCarCapacity();
regulations = CarDriver1.getRegulations();
did=CarDriver1.getDid();
reply = "I recieved your connection"+name;
outToClient.write(reply.getBytes(),0,reply.length());
outToClient.write("\\n".getBytes(),0,1);
outToClient.flush();
try
{
System.out.println("Closing Socket");
datain.close();
outToClient.close();
socket.close();
}
catch(IOException ioe)
{
System.out.println("Unable to Close Socket");
}
//String query = "Insert Into EECE 350Project
values(name='"+name+"',did="+did+",XLocation="+location.coordinateX+")";
}
else
{
System.out.println("Hey");
Regulations Pedregulations;
int pid=0;
Coordinates Pedlocation;
Coordinates PedDestination;
Pedestrian Pedestrian1 = (Pedestrian)
datain.readObject();
pid = Pedestrian1.pid;
Pedlocation = Pedestrian1.currentLocation;
PedDestination = Pedestrian1.Destination;
reply= "I recieved your connection";
System.out.println(pid);
outToClient.write(reply.getBytes(),0,reply.length());
outToClient.write("\\n".getBytes(),0,1);
outToClient.flush();
//outToClient.writeBytes(reply);
try
{
System.out.println("Closing Socket");
datain.close();
outToClient.close();
socket.close();
}
catch(IOException ioe)
{
System.out.println("Unable to Close Socket");
}
}
}
catch (IOException ex)
{
Logger.getLogger(SkillsServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(SkillsServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SQLException ex)
{
Logger.getLogger(SkillsServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
try
{
System.out.println("closing socket");
datain.close();
dataout.close();
socket.close();
}
catch (IOException e)
{
System.out.print('.');
}
}
}
}
The client code : Pedestrian for example
package eece350;
import java.io.Serializable;
import java.io.*;
import java.net.*;
/**
*
* #author user
*/
public class Pedestrian implements Serializable
{
public int pid=0;
public Coordinates currentLocation;
public Coordinates Destination;
public Regulations preferences;
public Pedestrian(Coordinates currentLocation,Coordinates Destination,int
pid,Regulations preferences)
{
this.pid=pid;
this.Destination=Destination;
this.currentLocation=currentLocation;
this.preferences=preferences;
}
public static void main(String argv[]) throws Exception
{
Socket clientSocket = new Socket("localhost", 7171);
ObjectOutputStream outToServer = new
ObjectOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
//ObjectInputStream inFromServer = new
ObjectInputStream(clientSocket.getInputStream());
int pid =0;
double XLocation = 2;
double YLocation = 2;
double XDestination = 4;
double YDestination = 4;
String modifiedSentence = "";
Coordinates currentLocation = new Coordinates(XLocation,YLocation);
Coordinates Destination = new Coordinates(XDestination,YDestination);
Regulations regulations = new Regulations("yes","No","yes","No");
Pedestrian pedestrian1 = new
Pedestrian(currentLocation,Destination,pid,regulations);
outToServer.writeObject(pedestrian1);
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
outToServer.close();
inFromServer.close();
outToServer.flush();
clientSocket.close();
}
}
Please someone help me :(
Effectively you are calling readObject() twice (but there is only one object on the stream).
The problem starts here:
if(datain.readObject().getClass()==CarDriver.class)
With this call, you are consuming the object, but not using it. Then you call readObject() again, which expects another object (but none exists).
Replace with:
Object object = datain.readObject(); // Read it once
if(object.getClass()==CarDriver.class) {
CarDriver carDriver1 = (CarDriver)object;
// process carDriver1;
}
else {
Pedestrian pedestrian1 = (Pedestrian)object;
// process pedestrian1
}
Have you tried:
Object object = datain.readObject();
if (object instanceof CarDriver) {
CarDriver carDriver1 = (CarDriver)object;
// process carDriver1;
}
else if (object instanceof Pedestrian) {
Pedestrian pedestrian1 = (Pedestrian)object;
// process pedestrian1
}
EDIT:
Replace this:
Pedestrian Pedestrian1 = (Pedestrian)datain.readObject();
With:
Pedestrian Pedestrian1 = (Pedestrian)object;

Java https proxy (using https.proxyPort and https.proxyHost)

I was making a Java application that relies on setting http.proxyPort and http.proxyHost. There are two processes: One is the regular program, the other is the proxy. I have a simple socket listener running on http.proxyPort (which I control). It's as simple as
while (true) {
try {
Socket connection = server.accept();
Handler handler = new Handler(connection);
handler.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
So whenever "process 1" makes an http request - like
URL yahoo = new URL("http://www.google.ca/");
URLConnection yc = yahoo.openConnection();
System.out.println(yc.getClass().getName());
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
It goes through the proxy. Now what if the client is using an HTTPS protocol? Like instead use https://google.ca? There's a property https.proxyPort and https.proxyHost, but I've literally been trying for months (on and off, it's not too important) without luck. I've read a bunch of threads (I will list some at the end so you know I have done something).
My closest attempt so far:
Server
try {
System.setProperty("javax.net.ssl.keyStore", "test.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "2520xe");
SSLServerSocketFactory sslserversocketfactory =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket =
(SSLServerSocket) sslserversocketfactory.createServerSocket(9999);
System.out.println("Ready");
SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
OutputStream toClient = sslsocket.getOutputStream();
toClient.write(("HTTP/1.0 200 Connection established\n" +
"Content-Length: " + "Shut down!".getBytes().length
+ "\r\n").getBytes("utf-8"));
toClient.write("Shut down!".getBytes("utf-8"));
toClient.close();
} catch (Exception exception) {
exception.printStackTrace();
}
Client
try {
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("https.proxyPort", "9999");
URL yahoo = new URL("https://www.google.ca/");
URLConnection yc = yahoo.openConnection();
System.out.println(yc.getClass().getName());
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
And I get this error javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection? I googled it but came up with some mail stuff instead.
Basically, I need to create a java proxy server, that's set to the client by the https.proxyPort and https.proxyHost flags, and can send data back to the client app, which may not be modified in any way (it's just using URL connection = new URL("https://..."))
A few of the sites I tried...
creating a Java Proxy Server that accepts HTTPS
http://stilius.net/java/java_ssl.php
There was something else about getting Java to accept all certificates, but I can't find any of the links. I have the code, but I encountered more errors than the thing I'm doing right now, but I can include it if it helps (I didn't initially because this is already a long question)
As auntyellow commented: you don't need to do any SSL-fiddling yourself. Basically https-proxying is about forwarding binary data between two parties.
To cite draft-luotonen-web-proxy-tunneling-01.txt:
CLIENT -> SERVER SERVER -> CLIENT
-------------------------------------- -----------------------------------
CONNECT home.netscape.com:443 HTTP/1.0
User-agent: Mozilla/4.0
<<< empty line >>>
HTTP/1.0 200 Connection established
Proxy-agent: Netscape-Proxy/1.1
<<< empty line >>>
<<< data tunneling to both directions begins >>>
So basically you need to ensure you trust your client enough to connect from your proxies firewall-position to the given host and port. Because of this common practice is to limit allowed port to 443, reject connection to localhost and from "untrusted" parties.
This is a "simple" server which is usable as https.proxy in Java if you are not jet convinced:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created for http://stackoverflow.com/q/16351413/1266906.
*/
public class Server extends Thread {
public static void main(String[] args) {
(new Server()).run();
}
public Server() {
super("Server Thread");
}
#Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(9999)) {
Socket socket;
try {
while ((socket = serverSocket.accept()) != null) {
(new Handler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace(); // TODO: implement catch
}
} catch (IOException e) {
e.printStackTrace(); // TODO: implement catch
return;
}
}
public static class Handler extends Thread {
public static final Pattern CONNECT_PATTERN = Pattern.compile("CONNECT (.+):(.+) HTTP/(1\\.[01])",
Pattern.CASE_INSENSITIVE);
private final Socket clientSocket;
private boolean previousWasR = false;
public Handler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
String request = readLine(clientSocket);
System.out.println(request);
Matcher matcher = CONNECT_PATTERN.matcher(request);
if (matcher.matches()) {
String header;
do {
header = readLine(clientSocket);
} while (!"".equals(header));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(clientSocket.getOutputStream(),
"ISO-8859-1");
final Socket forwardSocket;
try {
forwardSocket = new Socket(matcher.group(1), Integer.parseInt(matcher.group(2)));
System.out.println(forwardSocket);
} catch (IOException | NumberFormatException e) {
e.printStackTrace(); // TODO: implement catch
outputStreamWriter.write("HTTP/" + matcher.group(3) + " 502 Bad Gateway\r\n");
outputStreamWriter.write("Proxy-agent: Simple/0.1\r\n");
outputStreamWriter.write("\r\n");
outputStreamWriter.flush();
return;
}
try {
outputStreamWriter.write("HTTP/" + matcher.group(3) + " 200 Connection established\r\n");
outputStreamWriter.write("Proxy-agent: Simple/0.1\r\n");
outputStreamWriter.write("\r\n");
outputStreamWriter.flush();
Thread remoteToClient = new Thread() {
#Override
public void run() {
forwardData(forwardSocket, clientSocket);
}
};
remoteToClient.start();
try {
if (previousWasR) {
int read = clientSocket.getInputStream().read();
if (read != -1) {
if (read != '\n') {
forwardSocket.getOutputStream().write(read);
}
forwardData(clientSocket, forwardSocket);
} else {
if (!forwardSocket.isOutputShutdown()) {
forwardSocket.shutdownOutput();
}
if (!clientSocket.isInputShutdown()) {
clientSocket.shutdownInput();
}
}
} else {
forwardData(clientSocket, forwardSocket);
}
} finally {
try {
remoteToClient.join();
} catch (InterruptedException e) {
e.printStackTrace(); // TODO: implement catch
}
}
} finally {
forwardSocket.close();
}
}
} catch (IOException e) {
e.printStackTrace(); // TODO: implement catch
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace(); // TODO: implement catch
}
}
}
private static void forwardData(Socket inputSocket, Socket outputSocket) {
try {
InputStream inputStream = inputSocket.getInputStream();
try {
OutputStream outputStream = outputSocket.getOutputStream();
try {
byte[] buffer = new byte[4096];
int read;
do {
read = inputStream.read(buffer);
if (read > 0) {
outputStream.write(buffer, 0, read);
if (inputStream.available() < 1) {
outputStream.flush();
}
}
} while (read >= 0);
} finally {
if (!outputSocket.isOutputShutdown()) {
outputSocket.shutdownOutput();
}
}
} finally {
if (!inputSocket.isInputShutdown()) {
inputSocket.shutdownInput();
}
}
} catch (IOException e) {
e.printStackTrace(); // TODO: implement catch
}
}
private String readLine(Socket socket) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int next;
readerLoop:
while ((next = socket.getInputStream().read()) != -1) {
if (previousWasR && next == '\n') {
previousWasR = false;
continue;
}
previousWasR = false;
switch (next) {
case '\r':
previousWasR = true;
break readerLoop;
case '\n':
break readerLoop;
default:
byteArrayOutputStream.write(next);
break;
}
}
return byteArrayOutputStream.toString("ISO-8859-1");
}
}
}
Default java SE7 implementation of URLConnection for HTTPS protocol uses parameters
https.proxyHost and https.proxyPort
Add to Tomcat:
-Dhttps.proxyHost="192.168.121.31" -Dhttps.proxyPort="3128"

Java server , client program

The code below should allow the user to enter a URL and have it return the ip address of that website but it's not working.
The application is a console application. I had it working at one time but I don't know why it won't work now.
Here is the error i am getting when the users enters a website to get the ip address from
IOException: java.net.SocketException: Connection reset
HERE IS MY CLIENT CODE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6052;
if (args.length > 0) {
hostname = args[0];
}
Socket clientSocket = null;
PrintWriter os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(hostname, port);
os = new PrintWriter(clientSocket.getOutputStream(), true);
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
if (clientSocket == null || os == null || is == null) {
System.err.println("Something is really wrong. ");
return;
}
try {
if (args.length != 2) {
System.out.print("Enter a www web address (must have www!) ");
BufferedReader br = new BufferedReader(new InputSreamReader(Sy.in))
String keyboardInput = br.readLine();
os.println(keyboardInput);
} else {
os.println(args[1]);
}
String responseLine = is.readLine();
System.out.println("The IP address of " + args[1] + "is" + responseLine);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
HERE IS MY SERVER CODE
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
int port = 6052;
Server server = new Server(port);
server.startServer();
}
ServerSocket echoServer = null;
Socket clientSocket = null;
int numConnections = 0;
int port;
public Server(int port) {
this.port = port;
}
public void stopServer() {
System.out.println("Server working hold on a min.");
System.exit(0);
}
public void startServer() {
try {
echoServer = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Server is now started and is waiting for Clients.");
while (true) {
try {
clientSocket = echoServer.accept();
numConnections++;
new Thread(new ServerConnection(clientSocket, numConnections,
this)).start();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class ServerConnection implements Runnable {
private static BufferedReader is;
private static PrintStream os;
private static Socket clientSocket;
private static int id;
private static Server server;
public ServerConnection(Socket clientSocket, int id, Server server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println( "Connection " + id + " established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
line = is.readLine();
System.out.println( "Received " + line + " from Connection " + id + "." );
InetAddress hostAddress = InetAddress.getByName(line);
String IPaddress = hostAddress.getHostAddress();
os.println(IPaddress);
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
With no arguments, host will be localhost, user will be propted for a website. ArrayOutOfBoundsException because you didn't check the arguments.
With one argument, it is the host. Passing a site will not work because the site won't work as expected.
Running with two arguments, it works if the first argument is localhost.

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket.
Then I send the request to the server and I see the server gets it.
But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.
I am referring to the block ################
Do you know any possible reasons?
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyMain {
public static void main(String argv[]) {
int proxyPort = 55554;
String proxyAddr = "127.0.0.1";
ServerSocket proxySocket = null;
try {
proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
System.out.println();
while (true) {
Socket client = null;
Socket sockServ = null;
BufferedReader inClient = null;
PrintWriter outClient = null;
BufferedReader inServer = null;
PrintWriter outServer = null;
String request = new String();
String tmp = new String();
String reply = new String();
String tmpReply = new String();
try {
client = proxySocket.accept();
System.out.println("Connected to: ");
System.out.println(client.getInetAddress().toString());
System.out.printf("On port %d\n", client.getPort());
System.out.println();
inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
outClient = new PrintWriter(client.getOutputStream(), true);
}
/*catch (IOException e) {
System.err.println("Couldn't get I/O for connection accepted");
System.exit(1);
}*/
catch (Exception e) {
System.out.println("Error occurred!");
System.exit(1);
}
System.out.println("Received request:");
try{
for (int i = 0; i<2; i++) {
tmp = inClient.readLine();
request = request + tmp;
}
inClient.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read mhttp request!");
System.exit(1);
}
System.out.println(request);
System.out.println();
try {
sockServ = new Socket("127.0.0.1", 55555);
outServer = new PrintWriter(sockServ.getOutputStream(), true);
inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: 127.0.0.1:55555");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
System.exit(1);
}
outServer.println(request);
outServer.close();
try {
#################################################
while ((tmpReply = inServer.readLine()) != null) {
System.out.println(tmpReply);
reply = reply + tmpReply;
}
inServer.close();
sockServ.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read from server!");
System.exit(1);
}
outClient.println(reply);
outClient.close();
try {
client.close();
}
catch (IOException ioe) {
System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
}
}
}
}
UPDATE:
It seems that if I do:
boolean res = inServer.ready();
it always return false.
So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?
When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.
This works, maybe you can get some ideas from it...
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Categories