iterative dictionary server in java - java

what it do..
1. an iterative dictionary server that is listening clients requests..
2. connection will be established..
3. server will accept input string from client..
4. then server will search meaning of string from a file..
5. then server will return meaning to the client..
problem is with the while loop of server.. if it finds word it will send that word's meaning to client..fine.. but if word is not found... this
if(d.equals(null)){
input="No knowledge";
out.println(input);
out.flush();
}
doesn't execute... client says null and server says null exception...
what i am doing wrong here... i'm not getting it...!!
i have tried to changed this code...
client-server online dictionary program in java
client:
import java.io.;
import java.net.;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class DCC1 {
public static void main(String[] args) throws IOException {
final int PORT = 8888;
Socket s = null;
PrintWriter out = null;
try {
s = new Socket("localhost", PORT);
out = new PrintWriter(s.getOutputStream()); // Output stream to the server
}
catch (UnknownHostException ex) {
System.err.println("Unknown host: " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
catch (IOException ex) {
System.err.println("Cannot get I/O for " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
Scanner user = new Scanner(System.in); // Scanning for user input
System.out.print("Enter String: ");
String input;
input = user.next(); // Hold the input from the user
out.println(input); // Send it to the server
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream( )));
System.out.println(br.readLine());
out.close();
s.close();
}
}
server:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class DSC1
{
public static void main(String[] args) throws IOException
{
final int PORT = 8888;
final String FILE_NAME = "dictionary.dat";
ServerSocket server = new ServerSocket(PORT);
Socket s = null;
PrintWriter out = null;
Scanner in = null;
FileInputStream fin = null;
ObjectInputStream oin = null;
while (true)
{
try
{
s = server.accept();
}
catch (IOException ex)
{
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
System.out.println("Accepted connection from client");
try
{
in = new Scanner(s.getInputStream()); // Input stream from the client
out = new PrintWriter(s.getOutputStream()); // Output stream to the client
String temp = in.next(); // String holding the word sent from the client
System.out.println("From the client " + temp);
String input = null;
fin = new FileInputStream(FILE_NAME);// The dictionary file
oin = new ObjectInputStream(fin);
dictionary d = (dictionary)oin.readObject();
while(d!= null)
{
System.out.println("in loop...");
if(d.name.equals(temp)){
input=d.meaning;
d.printDic();
out.println(input);
out.flush();
break;
}
d = (dictionary)oin.readObject();
if(d.equals(null))
{
input="No knowledge";
out.println(input);
out.flush();
}
}
}
catch (ClassNotFoundException|IOException ex)
{
System.err.println("Exception: " + ex.getMessage());
System.out.println("Closing connection with client");
in.close();
System.exit(1);
}
in.close();
}
}
}

Don't use d.equals(null). If you want to check if d is null, just do if (d==null).
Why? There's no way this can return true, so probably that's the reason why this code never executes and you don't get what you expect.

Related

how to run config server when the port is args[0] in eclipse

This is my simple server program with java's ServerSocket class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
while (true)
{
try {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client...on " + port);
Socket client = server.accept();
System.out.println("Client from /" + client.getInetAddress() + " connected.");
BufferedReader rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
Writer out = new OutputStreamWriter(client.getOutputStream());
String nameClient = rdr.readLine();
System.out.println("Client " + nameClient + " wants to start a game.");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
I am trying to run config the server
but it keeps on saying this "Usage: java StartServer ".
I want to know how can I config the port when the port is args[0].
This is in Eclipse, by the way.
If it keeps saying "Usage: java StartServer" it therefore means this code
System.err.println("Usage: java StartServer <port>");
Is always been executed which means the condition
args.length != 1
Is always true. This could mean args.length = 0 or args.length > 1
Did you make eclipse pass the port number when running your application? That is did you configure any command line arguments to be used? I'm not a user eclipse so I can't help you here. See if this tutorial is helpful http://www.concretepage.com/ide/eclipse/how-to-pass-command-line-arguments-to-java-program-in-eclipse or you could try to find some other tutorial.
Also make sure you didn't pass too many arguments than is required because that will also make the condition to return true. Just pass as many arguments to make the condition args.length != 1 fail which is having 1 argument.
You can also see this question with help configuring command line arguments in eclipse.
This is my practice for you.
Copy and complete your code.
Select menu clicking right button of your mouse, Run > Run Configurations
Select Arguments tab and type a port number whatever you want your server to wait for client connection then, run it.
Test it with your client socket program.
This is my practice using client socket programming.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleClientSocketTest {
public static void main(String[] args) {
BufferedReader rdr = null;
Socket sock = null;
PrintWriter out = null;
try{
sock = new Socket("localhost", 9999);
rdr = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
out = new PrintWriter(sock.getOutputStream(), true);
String toServer = "hello...";
out.println(toServer + "i wants to start a game.");
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
if(fromServer == null) System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
rdr.close();
out.flush();
out.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Send a message to the server first,
out.println(toServer + "i wants to start a game.");
then, receive from the server.
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
There is one more thing to tell you about your server program.
This is a customized version of yours.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
while (true) {
BufferedReader rdr = null;
PrintWriter out = null;
int clientConnectionCnt = 0;
try {
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
if(client.isConnected())
{
System.out.println("Client from /" + client.getInetAddress() + " connected.");
String nameClient = null;
try {
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
System.out.println("clientConnectionCnt....." + clientConnectionCnt++);
nameClient = rdr.readLine();
out.println("Yes, You can");
if(nameClient == null) break;
System.out.println("Client: " + nameClient);
} catch (IOException e) {
e.printStackTrace();
break;
} finally {
out.flush();
rdr.close();
out.close();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
try {
server.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
First, you should create a server socket outside of while statement not in a while.
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
Just wait in a while statement util client socket accepting.
while (true) {
.... skip ...
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
Then, create in/out stream of client socket.
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
Finally, read and write a message with the socket's stream.
nameClient = rdr.readLine();
out.println("Yes, You can");
Regards, Rach.

socket closed exception occurs in an infinite loop

I'm supposed to write a program that take some .class files as service and they should be loaded and do the service. I'm have done it using socket programming but since I have made it multi-threaded so services can be used by any number of clients, i'm getting socket closed exception which occurs in an infinite while loop after each client thread is done. Even with one client i still get this exception. the only time that i do not get exception is when there is no class to load which i use break. I've tried to find the problem and searched a lot but I couldn't find anything.
//this is main class for server side
package reg.main;
import java.net.*;
import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
public class Application{
private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);
public static void main(String[] args){
while(true){
InputStream input = null;
Properties prop = new Properties();
try{
String filename = "config.properties";
input = Application.class.getClassLoader().getResourceAsStream(filename);
if(input == null){
System.out.println("Sorry, unable to find " + filename);
}
prop.load(input);
}
catch(IOException ex){
System.out.println("properties file does not exist.");
}
try{
String port = prop.getProperty("port");
int portNo = Integer.parseInt(port);
ServerSocket serverSocket = new ServerSocket(portNo);
LOGGER.debug("Server is listening... on port " + portNo);
ExecutorService service = Executors.newFixedThreadPool(1);
service.execute(new Server(serverSocket.accept()));
serverSocket.close();
service.shutdown();
}catch (IOException e) {
System.out.println("Could not close socket");
System.exit(1);
}
}
}
}
// this is server side code
package reg.main;
import java.net.*;
import java.io.*;
import reg.entity.*;
import reg.utility.*;
import reg.service.*;
import reg.dao.*;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Server implements Runnable{
private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);
private Socket clientSocket;
public Server(Socket clientSocket){
LOGGER.debug("Connection is Established.");
this.clientSocket = clientSocket;
}
public void run(){
ObjectOutputStream outToClient = null;
ObjectInputStream inFromClient = null;
try{
outToClient = new ObjectOutputStream(clientSocket.getOutputStream());
inFromClient = new ObjectInputStream(clientSocket.getInputStream());
}
catch(IOException ex){
LOGGER.error("There is a problem in reading or writing.");
}
while(true){
try{
String userOption =(String)inFromClient.readObject();//while printing stack trace, it says there is something wrong with this line. i don't know why!
System.out.println(userOption);
userOption = DataEditor.editOptionInputInfo(userOption); //this is a custom method
Map<String,Service> mapper= CustomClassLoader.loadClass(); //in class loader .class files will be loaded and an object of each of them will be sent in a map
if(mapper == null){
LOGGER.debug("no class file found to be loaded.");
clientSocket.close();
break;
}
List<String> classNames = CustomClassLoader.getClassNames();
boolean ckeckedUserOption = Validation.validUserOption(classNames,userOption);
if(ckeckedUserOption == false){
LOGGER.error("client has entered the wrong option.");
}
System.out.println(userOption + "in server class------------- before loading class");
Service service = mapper.get(userOption);
List<String> parameters = service.getRequiredParameters();
if(parameters.size() == 0){
LOGGER.debug("There is a problem with loaded classes.");
}
outToClient.writeObject(parameters);
LOGGER.debug("required parameters was sent to client.");
List<String>info = (List<String>)inFromClient.readObject();
LOGGER.debug("Information from client has been sent.");
if(info.size() == 0){
LOGGER.error("client has not put information. Try again.");
System.exit(2);
}
String result = service.doOperation(info);
outToClient.writeObject(result);
LOGGER.debug("Result of required service was sent to client.");
inFromClient.close();
outToClient.close();
//clientSocket.close();
}catch(IOException ex){
LOGGER.error("Exception caught when trying to listen on port "
+ " or listening for a connection");
ex.printStackTrace();
}
catch(ClassNotFoundException ex){
LOGGER.error("class was not found.");
}
}
}
}
// this is client side
package reg.main;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//Client class
public class Client{
private final static Logger LOGGER = LoggerFactory.getLogger(Client.class);
public static void main(String[] args){
Socket clientSocket = null;
String userOption;
InputStream inputStream = null;
Properties prop = new Properties();
try{
String filename = "config.properties";
inputStream = Client.class.getClassLoader().getResourceAsStream(filename);
if(inputStream == null){
System.out.println("Sorry, unable to find " + filename);
}
prop.load(inputStream);
}
catch(IOException ex){
System.out.println("properties file does not exist.");
}
try{
Scanner input = new Scanner(System.in);
System.out.println("Do you want to sign in or login? put the file name in:");
String path = input.next();
LOGGER.debug("User entered " + path + " as the service option.");
String port = prop.getProperty("port");
int portNo = Integer.parseInt(port);
FileReader fileReader = new FileReader(path);
BufferedReader reader = new BufferedReader(fileReader);
userOption = reader.readLine();
clientSocket = new Socket("192.168.121.114", portNo);
System.out.println("client is connected to the server.");
ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream());
outToServer.writeObject(userOption);
LOGGER.debug("sent the user option to server ==> " + userOption);
List<String> listOfparams =(List<String>)inFromServer.readObject();
LOGGER.debug("List of Requierements in Client " + listOfparams);
List<String> info = new ArrayList<String>();
for(String param : listOfparams){
System.out.println("Enter your " + param + ": ");
info.add(input.next());
}
outToServer.writeObject(info);
String result = (String)inFromServer.readObject();
LOGGER.debug("The result of required service: " + result);
System.out.println(clientSocket.isClosed());
inFromServer.close();
outToServer.close();
clientSocket.close();
} catch (UnknownHostException e) {
LOGGER.error("Don't know about host ");
System.exit(1);
} catch (IOException e){
LOGGER.error("Couldn't get I/O for the connection to the host or there is no service for loading");
System.exit(1);
}
catch(ClassNotFoundException ex){
LOGGER.error("class does not found.");
}
}
}
I appreciate any help. Thank u in advance
Use break in catch
try{
String filename = "config.properties";
input = Application.class.getClassLoader().getResourceAsStream(filename);
if(input == null){
System.out.println("Sorry, unable to find " + filename);
}
prop.load(input);
}
catch(IOException ex){
System.out.println("properties file does not exist.");
break; // this make program to go out of the loop
}

Server, Client socket implementation

Am writing a Server, client chat program using Java Socket. Here is my code for the Server socket class.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine();
output.println(inputLine);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
The client is able to make a connection and send a message to the server. The server can also receive the messages sent by the client. The problem is that when the message is sent from the server, the client does not receive the message. Here is my client socket code.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) throws Exception
{
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true)
{
System.out.println("Client: ");
line = clientInput.readLine();
output.println("Server: " + line );
if(line.equals("quit"))
{
break;
}
}
}
input.close();
clientInput.close();
output.close();
}
}
Server side:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println("Client request: " + inputLine);
String resp = "some response as you need";
output.println(resp);
System.out.println("Server response: " + resp);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
Client side:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String inputStr = clientInput.readLine();
output.println(inputStr);
System.out.println("Client: " + inputStr);
if (inputStr.equals("quit")) {
break;
}
String serverResp = input.readLine();
output.println("Server: " + serverResp);
}
}
}
}
It is tested.
It's always a good idea to flush your output streams when you are done with them, the info you are sending may have buffered.
The server is expecting an extra line from the client input here:
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine(); // <--- here
The client is not reading from the InputStream called input it gets when it connects to the server. It is only reading the local console input from clientInput.
In the while loop in Client.java you need something like this after the quit block to get the server's response:
System.out.println("Server: " + input.readLine());

Server not receiving in socket communication

I'm trying to make a Java program in which the server generates a random number and, after establishing a connection with a client, lets it guess the number. However, they both don't seem able to receive each others' messages.
Server side:
package numberguessserv;
import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class NumberGuessServ {
public static void main(String[] args) {
Scanner inpkb = new Scanner(System.in);
Random randomGenerator = new Random();
int randomNum = randomGenerator.nextInt(10);
String number = Integer.toString(randomNum);
int port;
boolean isGuessed = false;
String msgReceived;
Socket connect = new Socket();
System.out.print("port: ");
port = inpkb.nextInt();
try {
ServerSocket clSock = new ServerSocket(port);
System.out.println("Waiting...");
connect = clSock.accept();
System.out.println("Connection established with"+connect.getInetAddress());
InputStreamReader isr = new InputStreamReader(connect.getInputStream());
BufferedReader isrBuff = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(connect.getOutputStream());
BufferedWriter oswBuff = new BufferedWriter(osw);
while (!isGuessed) {
msgReceived = isrBuff.readLine();
System.out.println("Number received: "+msgReceived);
if (msgReceived.equals(number)) {
isGuessed = true;
oswBuff.write("Right!");
oswBuff.flush();
}
else {
oswBuff.write("Wrong!");
oswBuff.flush();
}
if (isGuessed)
System.out.println("Number was guessed right.");
else
System.out.println("Number was guessed wrong.");
}
}
catch (Exception ex) {
System.out.println("An exception has occurred: "+ex);
}
finally {
try {
connect.close();
}
catch (Exception ex) {
System.out.println("An exception has occurred: "+ex);
}
}
}
}
Client side:
package numberguessclient;
import java.io.*;
import java.util.Scanner;
import java.net.*;
public class NumberGuessClient {
public static void main(String[] args) {
Scanner inpkb = new Scanner(System.in);
int port;
String IP;
boolean isGuessed = false;
String number, msg;
Socket serv = new Socket();
System.out.print("IP: ");
IP = inpkb.next();
System.out.print("port: ");
port = inpkb.nextInt();
try {
serv = new Socket(IP,port);
System.out.println("Connetion established with"+serv.getInetAddress());
InputStreamReader isr = new InputStreamReader(serv.getInputStream());
BufferedReader isrBuff = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(serv.getOutputStream());
BufferedWriter oswBuff = new BufferedWriter(osw);
while (!isGuessed) {
System.out.print("number: ");
number = inpkb.next();
oswBuff.write(number);
oswBuff.flush();
System.out.println("Number sent.");
msg = isrBuff.readLine();
System.out.println("The reply was received: "+msg);
if (msg.equals("Right!")) {
isGuessed = true;
System.out.println(msg);
}
else {
System.out.println(msg+"\nTry again...");
}
}
}
catch (Exception ex) {
System.out.print("An exception has occurred: "+ex);
}
finally {
try {
serv.close();
}
catch (Exception ex) {
System.out.print("An exception has occurred: "+ex);
}
}
}
}
The readLine() waits for the end of line. Unless and until it gets a new line character, it will wait up there reading.
So, you need to give a new line characer '\n' every time you give an input to the output stream so that the readLine() reads a new line character and does not wait.
Currently in your code, you need to give a new line character everytime you are giving input by doing the following:
oswBuff.write("any message");
oswBuff.write('\n'); //add this statement everywhere you are writing to the output stream
oswBuff.flush();
This complies well for both the server as well as client.
That's expected. Both ends read using
isrBuff.readLine();
So, they both expect the other end to send a line. But none of them sends a line. They both do
oswBuff.write(number);
oswBuff.flush();
That sends some characters, but doesn send any newline character. The receiving end doesn't have any way to know that the end of line has been reached, and it thus continues blocking until it receives the EOL.

Simple Client Server Application, but something is going wrong

I am using Socket and ServerSocket classes to communicate on local host
client sends a no. to server and server computes square of no. and sends back to the client
// Client Class
import java.net.*;
import java.io.*;
class SocketDemo
{
public static void main(String...arga) throws Exception
{
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
System.out.println("Enter a number one digit");
int i=(System.in.read()-48); // will read only one character
System.out.println("Input number is "+i);
try
{
s = new Socket("127.0.0.1",10101);
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("Connection established, streams created");
}
catch(Exception e)
{
System.out.println("Exception in Client "+e);
}
pw.println(i);
System.out.println("Data sent to server");
String str = br.readLine();
System.out.println("The square of "+i+" is "+str);
}
}
// Server Side
import java.io.*;
import java.net.*;
class ServerSocketDemo
{
public static void main(String...args)
{
ServerSocket ss=null;
PrintWriter pw = null;
BufferedReader br = null;
int i=0;
try
{
ss = new ServerSocket(10101);
}
catch(Exception e)
{
System.out.println("Exception in Server while creating connection"+e);
}
System.out.print("Server is ready");
while (true)
{
System.out.println (" Waiting for connection....");
Socket s=null;
try
{
s = ss.accept();
System.out.println("Connection established with client");
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
i = new Integer(br.readLine());
System.out.println("i is "+i);
}
catch(Exception e)
{
System.out.println("Exception in Server "+e);
}
System.out.println("Connection established with "+s);
i*=i;
pw.println(i);
try
{
pw.close();
br.close();
}
catch(Exception e)
{
System.out.println("Exception while closing streams");
}
}
}
}
Please Help
On client side do this after sending data to server
pw.println(i);
pw.flush();

Categories

Resources