Exception : java.net.MalformedURLException: no protocol: /setwindowsagentaddr - java

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

Related

Open Source Java HTTP Codecs

I am writing a web server from the scratch. There I need a Http codec which can decode a string request (buffer) to an Http object and encode http object into Sting (buffer).
I found three Codecs,
Apache Codecs (can't use this because this is tightly coupled with their server coding structure)
Netty Codes (can't use this because this is tightly coupled with their server coding structure)
JDrupes Codecs (Has some concurrency issues)
But non of these can be used for my purpose. Are there any other Codecs I can use?
class SimpleHttpsServer implements Runnable {
Thread process = new Thread(this);
private static int port = 3030;
private String returnMessage;
private ServerSocket ssocket;
/************************************************************************************/
SimpleHttpsServer() {
try {
ssocket = new ServerSocket(port);
System.out.println("port " + port + " Opend");
process.start();
} catch (IOException e) {
System.out.println("port " + port + " not opened due to " + e);
System.exit(1);
}
}
/**********************************************************************************/
public void run() {
if (ssocket == null)
return;
while (true) {
Socket csocket = null;
try {
csocket = ssocket.accept();
System.out.println("New Connection accepted");
} catch (IOException e) {
System.out.println("Accept failed: " + port + ", " + e);
System.exit(1);
}
try {
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(csocket.getInputStream()));
PrintStream printStream = new PrintStream(new BufferedOutputStream(csocket.getOutputStream(), 1024),
false);
this.returnMessage = "";
InputStream inputStream = csocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// code to read and print headers
String headerLine = null;
while ((headerLine = bufferedReader.readLine()).length() != 0) {
System.out.println(headerLine);
}
// code to read the post payload data
StringBuilder payload = new StringBuilder();
while (bufferedReader.ready()) {
payload.append((char) bufferedReader.read());
}
System.out.println("payload.toString().length() " + payload.toString().length());
if (payload.toString().length() != 1 || payload.toString().length() != 0) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(payload.toString());
// Handle here your string data and make responce
// returnMessage this can store your responce message
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + this.returnMessage;
printStream.write(httpResponse.getBytes("UTF-8"));
printStream.flush();
}else {
/*String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
outStream.write(httpResponse.getBytes("UTF-8"));
outStream.flush();*/
}
printStream.close();
dataInputStream.close();
// csocket.close();
System.out.println("client disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/************************************************************************************/
public static void main(String[] args) {
new SimpleHttpsServer();
}
}
may be this one is help you

Java Server Thread Null Pointer Exception error raised after trying to encode / decode strings into UTF-8 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to create a program where a client and server send text messages to each other (in utf-8 string format) similar to how two phones text message each other. Eventually I will need to create four lines (two to encode/decode utf-8 string on server side) (two to encode/decode utf-8 string on client side) This program uses two threads, one for the client one for the server.
Screenshot of error in mac terminal (command prompt)
There were no errors before I changed the following lines of code:
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
There are three files: the main function file, the server file, and the client file. When the main function file runs, if the "-l" command line argument is present, the server file will run, otherwise the client will run.
Server file (DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
private static Socket socket;
boolean KeepRunning = true;
void ServerRun(String[] args)
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
System.out.println("Port number is: " + port_number1);
ServerSocket serverSocket = new ServerSocket(port_number1);
//SocketAddress addr = new InetSocketAddress(address, port_number1);
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//Reading the message from the client
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
//Shut down with zero-length message
if(MessageFromClientDecodedFromUTF8.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
//creating message to server send from standard input
String newmessage = "";
try {
// input the message from standard input
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null && KeepRunning==true )
{
newmessage += line + " \n ";
}
}
catch ( Exception e ) {
System.out.println( e.getMessage() );
}
//Writing return message back to client
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Server.start();
}
}
Client file (DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
boolean KeepRunning = true;
private static Socket socket;
//static String[] arguments;
//public static void main(String[] args)
//{
// arguments = args;
//}
public DirectMessengerClient()
{
//System.out.println("test.");
}
public void ClientRun(String[] args)
{
Thread Client = new Thread ()
{
public void run()
{
System.out.println("Client thread is now running");
try
{
System.out.println("Try block begins..");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
while(KeepRunning)
{
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
if(MessageFromServer.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Client.start();
}
}
Main function file (DirectMessengerCombined.java):
public class DirectMessengerCombined
{
public static void main(String[] args)
{
DirectMessengerClient Client1 = new DirectMessengerClient();
DirectMessengerServer Server1 = new DirectMessengerServer();
for (int i = 0; i < args.length; i++)
{
if(!args[0].equals("-l"))
{
Client1.ClientRun(args);
}
switch (args[0].charAt(0))
{
case '-':
if(args[0].equals("-l"))
{
Server1.ServerRun(args);
}
}
i=args.length + 20;
}
}
}
My question is: How do I change the way the strings are encoded or decoded in order to send strings to the other side or how to solve the null pointer exception error?
It is because you are trying to get the inputstream of a socket before it exists:-
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
These two lines should be the other way around. :)
EDIT: Looking further at your code, you are creating BufReader1 (which is causing the error) and then creating br in exactly the same way, i.e. both are a BufferedReader of the socket. You only need one; having two will probably cause problems for the readers.

What is run() function doing in ProxyThread class if is not called anywhere?

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.

Java Socket why server can not reply client

I wanna write the code to let Client send a string to Server, Server print the string and reply a string, then Client print the string Server reply.
My Server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
My Client:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
are there some somethings wrong? if i remove the code "while(true) ..." in client class, it's OK.
you should add "\r\n" at the end of the String which write into stream.
example:
client :
string = "end";
out.write(string + "\r\n");
out.flush();
server :
out.write("to end" + "\r\n");
out.flush();
out.close();
System.out.println("end");
// break;
I don't see the server response.
You do a
System.out.println("br: " + string);
but not a
out.write(string);
out.flush();
Appand "\n" to end of the response from server.
outToClient.writeBytes(sb.toString() + "\n");
You are reading lines but you aren't writing lines. Add a newline, or call BufferedReader.newLine().

JAVA Chat Sever communicates with Iphone clients using TCP protocol

I want to develop demo of JAVA chat server which handles TCP protocol.
Clients will be I-phone.
How can i make communication between JAVA chat server and Objective C ?
I have tried
public class ChatServer {
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
ChatServer() throws IOException {
}
void run() {
try {
// 1. creating a server socket
providerSocket = new ServerSocket(2001, 10);
// 2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from "
+ connection.getInetAddress().getHostName());
// 3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
// in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
BufferedReader in1 = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
// out = new PrintWriter(socket.getOutputStream(),true);
int ch;
// String line="";
// do{
// ch=in1.read();
// line+=(char)ch;
//
// }while(ch!=-1);
String line = in1.readLine();
System.out.println("you input is :" + line);
// 4. The two parts communicate via the input and output streams
/*
* do { try { message = (String) in.readObject();
* System.out.println("client>" + message); if
* (message.equals("bye")) sendMessage("bye"); } catch
* (ClassNotFoundException classnot) {
* System.err.println("Data received in unknown format"); } } while
* (!message.equals("bye"));
*/
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
// in.close();
out.close();
providerSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ChatServer server = new ChatServer();
while (true) {
server.run();
}
}
}
and in objective C i have used
LXSocket *socket;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
socket = [[LXSocket alloc]init];
if ([socket connect:#"127.0.0.1" port:2001]) {
NSLog(#"socket has been created");
}
else {
NSLog(#"socket couldn't be created created");
}
#try {
[self sendData];
}#catch (NSException * e) {
NSLog(#"Unable to send data");
}
[super viewDidLoad];
}
-(IBAction)sendData{
// [socket sendString:#"M\n"];
[socket sendObject:#"Masfds\n"];
}
I am able to communicate but i am getting some unnecessary bits appended with Message which was sent from objective c.
output at server side:
Received from Connection 1.
Received U$nullĂ’
Suggest me some nice ways to resolve this issue.
i have solved this issue with this code:
//Server
package com.pkg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
public static void main(String args[]) {
int port = 6789;
ChatServer server = new ChatServer(port);
server.startServer();
}
// declare a server socket and a client socket for the server;
// declare the number of connections
ServerSocket echoServer = null;
Socket clientSocket = null;
int numConnections = 0;
int port;
public ChatServer(int port) {
this.port = port;
}
public void stopServer() {
System.out.println("Server cleaning up.");
System.exit(0);
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Server is started and is waiting for connections.");
System.out
.println("With multi-threading, multiple connections are allowed.");
System.out.println("Any client can send -1 to stop the server.");
// Whenever a connection is received, start a new thread to process the
// connection
// and wait for the next connection.
while (true) {
try {
clientSocket = echoServer.accept();
numConnections++;
Server2Connection oneconnection = new Server2Connection(
clientSocket, numConnections, this);
new Thread(oneconnection).start();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class Server2Connection implements Runnable {
BufferedReader is;
PrintStream os;
Socket clientSocket;
int id;
ChatServer server;
InputStream isr;
private static final int BUFFER_SIZE = 512; // multiples of this are
// sensible
public Server2Connection(Socket clientSocket, int id, ChatServer server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println("Connection " + id + " established with: "
+ clientSocket);
try {
isr = clientSocket.getInputStream();
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;
while (true) {
line = is.readLine();
if (line != null) {
System.out.println("Received " + line + " from Connection "
+ id + ".");
os.println("Hello this is server:" + line);
if (line.equalsIgnoreCase("stop")) {
serverStop = true;
break;
}
} else {
break;
}
// int n = Integer.parseInt(line);
// if (n == -1) {
// serverStop = true;
// break;
// }
// if (n == 0)
// break;
// os.println("" + n * n);
}
System.out.println("Connection " + id + " closed.");
is.close();
os.close();
clientSocket.close();
if (serverStop)
server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
}
//client
package com.pkg;
import java.io.*;
import java.net.*;
public class Requester {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6789;
// declaration section:
// clientSocket: our client socket
// os: output stream
// is: input stream
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
// Initialization section:
// Try to open a socket on the given port
// Try to open input and output streams
try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
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 everything has been initialized then we want to write some data
// to the socket we have opened a connection to on the given port
if (clientSocket == null || os == null || is == null) {
System.err.println( "Something is wrong. One variable is null." );
return;
}
try {
while ( true ) {
System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );
// int n = Integer.parseInt( keyboardInput );
// if ( n == 0 || n == -1 ) {
// break;
// }
if(keyboardInput.equalsIgnoreCase("stop")){
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
//objective c client
//
// RKViewController.m
// ConnectServer
//
// Created by Yogita Kakadiya on 10/27/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "RKViewController.h"
#interface RKViewController ()
#end
#implementation RKViewController
- (void)viewDidLoad
{
[super viewDidLoad];
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if ([socket connectToHost:#"192.168.2.3" onPort:6789 error:&err])
{
NSLog(#"Connection performed!");
[socket readDataWithTimeout:-1 tag:0];
}
else
{
NSLog(#"Unable to connect: %#", err);
}
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(#"Socket:DidConnectToHost: %# Port: %hu", host, port);
connected = YES;
if(connected)
{
NSData *message = [[NSData alloc] initWithBytes:"Ranjit\n" length:8];
[sock writeData:message withTimeout:-1 tag:0];
}
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(#"SocketDidDisconnect:WithError: %#", err);
connected = NO;
//We will try to reconnect
//[self checkConnection];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
//[self processReceivedData:data];
NSString *readMessage = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"RECIEVED TEXT : %#",readMessage);
[sock readDataWithTimeout:-1 tag:0];
//NSData *message = data;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end

Categories

Resources