Client.java
-----------------------------------------------------------------
/***********************************
Author: Rajneshwar Prasad
***********************************/
import java.io.*;
import java.net.*;
class Client
{ public static void main(String a[]) throws IOException
{ // Specify your server with a url or an IP address.
// if you try this on your system, insert your system name
// such as "pc107" in the server string instead of loopback.
String loopback = "127.0.0.1"; // "localhost" will also work.
String server = loopback;
// Open our connection to the server, at port 4444
Socket sock = new Socket(server,4444);
// Get I/O streams from the socket
BufferedReader dis = new BufferedReader(new InputStreamReader( sock.getInputStream() ));
PrintStream dat = new PrintStream(sock.getOutputStream() );
// Now we can just read from and write to the streams.
// Start with reading for this server.
String fromServer = dis.readLine();
System.out.println("Got this from server: " + fromServer);
String myReply = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
myReply = in.readLine();
dat.println(myReply);
fromServer = dis.readLine();
System.out.println("More from Server: "+ fromServer);
// All done. Close the connection.
sock.close();
}
}
-----------------------------------------------------------------
Server.java
-----------------------------------------------------------------
/***********************************
Author: Rajneshwar Prasad
***********************************/
import java.io.*;
import java.net.*;
public class Server
{ public static void main(String a[]) throws IOException
{ int port = 4444;
Socket client = null;
// Next we create the server socket that we will listen to.
ServerSocket servsock = new ServerSocket(port);
String query = "If you met me would you shake my hand, or sniff it?";
while (true)
{ // Wait for the next client connection
client = servsock.accept();
// Create the input and output streams for our communication.
PrintStream out = new PrintStream( client.getOutputStream() );
BufferedReader in = new BufferedReader(new InputStreamReader( client.getInputStream()));
// Now you can just write to and read from these streams.
// Send our query
out.println(query); out.flush();
// get the reply
String reply = in.readLine();
if (reply.indexOf("sniff") > -1)
{ System.out.println("On the Internet I know this is a DOG!");
out.println("You're a dog.");
}
else
{ System.out.println("Probably a person or an AI experiment");
out.println("You're a person or something.");
}
out.flush();
// All done. Close this connection
client.close();
}
}
}
-----------------------------------------------------------------
No comments:
Post a Comment