server client socket programming output difficulties - java

m new in socket programming...i hv to create a server that stores name & id from a client in a queue and then it stores all the inputs given by the client in another queue. when the client writes 'test', server retrieves all the stored data as the client types some value i.e. integer...when client types 'resume' server again starts storing client's given input in the queue...if client types 'exit' server sends back the client's name and id and starts waiting for a ne client. And the receives those info and closes the socket.
Problem faced:
m facing problem in retrieving the data from queues. when i type exit, i can see the name and id which i'm retriving through the for loop. if i put this line outToClient.writeBytes("Thank You!"+'\n'); after the for loop then it shows the client's name & id but the client doest go off.
in the if else condition while checking for 'test' again i'm facing problem in retrieving data. server asks for integer..client types an integer and then i dont get the data from server.
here is my code
Server Side:
import java.io.*;
import java.net.*;
import java.util.*;
class server
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String replySentence;
ServerSocket welcomeSocket= new ServerSocket(6789);
while(true)
{
System.out.println("#########Server Waiting#########");
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
Queue<String> qe = new LinkedList<String>();
outToClient.writeBytes("Enter your Name and ID Please..."+'\n');
for(int i=0;i<=1;i++)
{
clientSentence = inFromClient.readLine();
qe.add(clientSentence);
}
outToClient.writeBytes("Thank you! You may now proceed further..."+'\n');
Queue<String> chatq = new LinkedList<String>();
clientSentence = inFromClient.readLine();
while(!clientSentence.equals("exit"))
{
if(clientSentence.equals("test"))
{
outToClient.writeBytes("Enter Integers to fetch data or 'resume' to continue..."+'\n');
clientSentence = inFromClient.readLine();
while(!clientSentence.equals("resume"))
{
replySentence = chatq.remove();
outToClient.writeBytes(replySentence+'\n');
clientSentence = inFromClient.readLine();
}
if(clientSentence.equals("resume"))
{
outToClient.writeBytes("You may now proceed again..."+'\n');
clientSentence = inFromClient.readLine();
}
}
else
{
chatq.add(clientSentence);
clientSentence = inFromClient.readLine();
}
}
if(clientSentence.equals("exit"))
{
outToClient.writeBytes("Client Name & ID: "+'\n');
for(int i=0;i<=1;i++)
{
replySentence = qe.remove();
outToClient.writeBytes(replySentence+'\n');
}
}
}
}
}
Client Side:
import java.io.*;
import java.net.*;
import java.util.*;
class client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
InetAddress inetAddress=InetAddress.getLocalHost();
System.out.println(inetAddress);
Socket clientSocket = new Socket(inetAddress,6789);
while(true)
{
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence+'\n');
for(int i=0;i<=1;i++)
{
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence+'\n');
}
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
while(!sentence.equals("exit"))
{
if(sentence.equals("test"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
while(!sentence.equals("resume"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
}
if(sentence.equals("resume"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
}
}
else
{
outToServer.writeBytes(sentence+'\n');
sentence = inFromUser.readLine();
}
}
if(sentence.equals("exit"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
for(int i=0;i<=1;i++)
{
modifiedSentence=inFromServer.readLine();
System.out.println(modifiedSentence + '\n');
}
clientSocket.close();
break;
}
}
}
}

I assume this is [homework] however...
You are mixing binary (DataOutputStream) with text (BufferedReader). You should use one or the other or you are bound to confuse yourself.
It appears you want to send text so I would use BufferedReader and PrintWriter. DataOutputStream is better suited for binary protocols.

Related

Client and Server PCs are not connecting within a LAN

I`m trying to connect a Java Client with a Server in the same LAN, client and server are in two different PCs.
Here goes my Client Code,
import java.io.*;
import java.net.*;
public class Client{
public static void main(String[] args) throws Exception{
String ip = "192.168.0.103";
int port = 9999;
Socket s = new Socket(ip,port);
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String msgin = " ";
String msgout = " ";
while(!msgin.equals("end")){
msgout = br.readLine();
dout.writeUTF(msgout);
msgin = din.readUTF();
System.out.println("Mr.Client : "+msgin);
}
}
}
The Server PC has a IP of 192.168.0.103 .
Here is the Server code,
import java.io.*;
import java.net.*;
public class Server{
public static void main(String[] args) throws Exception{
System.out.println("Server started ... ... ");
ServerSocket ss = new ServerSocket(9999);
System.out.println("Waiting for client request ... ... ");
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String msgin = " ";
String msgout = " ";
while(!msgin.equals("end")){
msgin = din.readUTF();
System.out.println("Mr.Server : "+msgin);
msgout = br.readLine();
dout.writeUTF(msgout);
dout.flush();
}
}
}
Whenever I`m running these codes, the Server shows it is waiting for the Client but after running Client, the Client becomes frozen for unlimited time, stays stuck, no output.
To be mentioned, the Client is running on a Ubuntu machine and Server is on a Windows one.
When I ran the Client and Server in Windows PC using localhost, it worked without any issue.
Some clue would mean great help. Thank you.

Java TCP Client-Server - stuck in infinite loops in both applications [duplicate]

This question already has answers here:
Importance of the new line "\n" in Java networking
(2 answers)
Closed 4 years ago.
I have a Client and a Server, they should have a communication in both ways. Everything worked well, client sent some information to server, and server did something with that information. Now that I tried to implement server replying to. After I've tried implementing that, both programs are now stuck in an infinite loop, waiting for information from the other side.
Here is my code for the server side:
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
logger.log(Level.INFO, "args[0]: {0} args[1]: {1} args[2]: {2} args[3] {3}", new Object[]{args[0], args[1], args[2], args[3]});
pathToExcel = args[0];
pathToDatabase = args[1];
numberOfAccounts = Integer.parseInt(args[2]);
portNumber = Integer.parseInt(args[3]);
listIE = new ArrayList<>();
listIE = Loader.getList(numberOfAccounts, pathToExcel);
DBBroker.createTables(pathToDatabase);
System.out.println("Check value: " + DBBroker.checkDB());
if (DBBroker.checkDB() == false) {
DBBroker.insertData();
DBBroker.insertDataBalance();
} else {
System.out.println("Data has already been inserted into the database");
}
startServer();
}
public static void startServer() throws IOException {
//ServerSocket ss = new ServerSocket(portNumber);
ServerSocket ss = new ServerSocket(portNumber);
logger.log(Level.INFO, "Server started on port number: {0}", portNumber);
try {
while (true) {
Socket clientSocket = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Client connected ");
//***************************************************************************
String answer = input.readLine();
//***************************************************************************
System.out.println("prosao readline");
//logger.info("Client logged in on port " +portNumber);
String[] niz = answer.split("_");
//System.out.println("niz: " +Arrays.toString(niz));
serverPortNumber = Integer.parseInt(niz[0]);
accountName = niz[1];
receiverName = niz[2];
amount = Integer.parseInt(niz[3]);
//System.out.println("Server port number: " +serverPortNumber + " accountname: " +accountName +" receiver name: " +receiverName + " amount: " +amount);
parseRequestFromClient();
System.out.println("Prosao request");
clientOutput.writeBytes("Kraj");
clientSocket.close();
}
//ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is my code for the client side:
public static void main(String[] args) throws IOException {
String messageFromServer = "";
logger.log(Level.INFO, "args[0]: {0} args[1]: {1} args[2]: {2} args[3] {3}", new Object[]{args[0], args[1], args[2], args[3]});
Socket socket = new Socket("localhost", Integer.parseInt(args[0]));
//logger.info("args[0]: " +args[0] +" args[1]: " +args[1] +" args[2]: " +args[2] +" args[3] " +args[3]);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String dataForServer = args[0]+"_"+args[1]+"_"+args[2]+"_"+args[3];
System.out.println("Data for server: " +dataForServer);
outputStream.writeBytes(dataForServer);
System.out.println("prosao dataforserver");
//***************************************************************************
String answer = input.readLine();
//***************************************************************************
System.out.println("prosao readline");
System.out.println(answer);
socket.close();
}
Server side gets stuck at the ss.accept() line, while the Client side gets stuck at input.readLine()
I didn't add the whole project because a large portion of it is not relevant to the problem and it has a lot of code.
Your server was blocking on readLine(). It blocks for a line terminator. The client was only sending a raw string. The solution is to send a line terminator with each raw string.
The same applies when the server responds to the client.
As Simon has pointed out a printwriter would be a good choice if your message protocol is to pass line terminated strings.

TCP Server response timeout

I have been tasked with getting a simple TCP Client to timeout. The client works as expected, however I cannot seem to get the client to timeout when the client does not receive an input for 3 seconds or more.
I have a basic understanding of SO_TIMEOUT, but can't get it to work here.
Please help
Here is my code:
TCPClient
private static final String host = "localhost";
private static final int serverPort = 22003;
public static void main(String[] args) throws Exception
{
try
{
System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
#SuppressWarnings("resource")
Socket client = new Socket(host, serverPort);
client.setSoTimeout(3000);
while(true)
{
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
String input = inFromUser.readLine();
outToServer.writeBytes(input + "\n");
String modedInput = inFromServer.readLine();
System.out.println("You Sent: " + modedInput);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println("Slept-in");
e.getStackTrace();
}
}
}
catch(SocketTimeoutException e)
{
System.out.println("Timed Out Waiting for a Response from the Server");
}
}
setSoTimeout doesn't do what you think it does. From the Javadoc:
With this option set to a non-zero timeout, a read() call on the
InputStream associated with this Socket will block for only this
amount of time.
It's a timeout for reads from the socket, so reads() will return after 3 seconds even if there's no data. It's not a timeout for socket inactivity - i.e. the socket won't disconnect after being idle for 3 seconds.

BufferedReader give more null character in string while using with TCP Socket

My TCP Server is like this.
import java.net.*;
import java.io.*;
public class NetTCPServer {
public static void main(String[] args) throws Exception{
ServerSocket sock;
sock = new ServerSocket(1122);
if(sock == null)
System.out.println("Server binding failed.");
System.out.println("Server is Ready ..");
do{
System.out.println("Waiting for Next client.");
Socket clientSocket = sock.accept();
if(clientSocket!=null)
System.out.println("Clinet accepted. "+sock.getInetAddress().getHostAddress());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
//DataInputStream in = new DataInputStream(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String name;
String pass;
String line;
name = in.readLine();
pass = in.readLine();
for(int i=0;i<name.length();i++)
System.out.print(name.charAt(i)+","); //see more null char are receiving here
System.out.println("");
System.out.println(name +" "+ name.length()+" \n" + pass+" "+pass.length());
}while(true);
}
}
And respective TCP Client is as follows.
import java.net.*;
import java.io.*;
public class NetTCPClient {
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getByName("localhost");
Socket sock;
sock = new Socket(addr,1122);
if(sock == null)
System.out.println("Server Connection failed.");
System.out.println("Waiting for some data...");
DataInputStream input = new DataInputStream(sock.getInputStream());
DataOutputStream output = new DataOutputStream(sock.getOutputStream());
String uname="ram";
String pass="pass";
output.writeChars(uname+"\n");// \n is appended just make to readline of server get line
output.writeChars(pass+"\n");
}
}
When i compiled both and the server is started and there after client is run, i get following output.
Server is Ready ..
Waiting for Next client.
Clinet accepted. 0.0.0.0
,r,,a,,m,,
ram7 pass9
The null character after each character receive is somewhat strange to me. To make me unable to compare the string with something stored in server.
What is those null characters and where does they come from.
You write characters but read lines of bytes. That won't work. If you're going to write characters, you need to read characters with precisely the same encoding. If you're going to write bytes, you need to read bytes. Specify your protocol precisely at the byte level and follow the specification in both the client and the server.
See this question for more information.

Communication between python client and java server

My aim is to send a message from python socket to java socket. I did look out on the resource mentioned above. However I am struggling to make the Python client talk to Java server. Mostly because (End of line) in python is different from that in java.
say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)
At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.
Could anybody please suggest a solution for a consistent talk between java and python.
Reference I used: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html
Update: I forgot to add, I am working on TCP.
My JAVA code goes like this:(server socket)
String fromclient;
ServerSocket Server = new ServerSocket (5000);
System.out.println ("TCPServer Waiting for client on port 5000");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while ( true )
{
fromclient = inFromClient.readLine();
if ( fromclient.equals("q") || fromclient.equals("Q") )
{
connected.close();
break;
}
else
{
System.out.println( "RECIEVED:" + fromclient );
}
}
}
My PYTHON code : (Client Socket)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data <> 'Q' and data <> 'q'):
client_socket.send(data)
else:
client_socket.send(data)
client_socket.close()
break;
OUTPUT::
ON PYTHON CONSOLE(Client):
SEND( TYPE q or Q to Quit):abcd ( pressing ENTER)
SEND( TYPE q or Q to Quit):efgh ( pressing ENTER)
SEND( TYPE q or Q to Quit):q ( pressing ENTER)
ON JAVA CONSOLE(Server):
TCPServer Waiting for client on port 5000
THE CLIENT /127.0.0.1:1335 IS CONNECTED
RECIEVED:abcdefghq
Append \n to the end of data:
client_socket.send(data + '\n')
ya..you need to add '\n' at the end of the string in python client.....
here's an example...
PythonTCPCLient.py
`
#!/usr/bin/env python
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.sendall("Hello\n")
data = sock.recv(1024)
print "1)", data
if ( data == "olleH\n" ):
sock.sendall("Bye\n")
data = sock.recv(1024)
print "2)", data
if (data == "eyB}\n"):
sock.close()
print "Socket closed"
`
Now Here's the java Code:
JavaServer.java
`
import java.io.*;
import java.net.*;
class JavaServer {
public static void main(String args[]) throws Exception {
String fromClient;
String toClient;
ServerSocket server = new ServerSocket(8080);
System.out.println("wait for connection on port 8080");
boolean run = true;
while(run) {
Socket client = server.accept();
System.out.println("got connection on port 8080");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if(fromClient.equals("Hello")) {
toClient = "olleH";
System.out.println("send olleH");
out.println(toClient);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if(fromClient.equals("Bye")) {
toClient = "eyB";
System.out.println("send eyB");
out.println(toClient);
client.close();
run = false;
System.out.println("socket closed");
}
}
}
System.exit(0);
}
}
`
Reference:Python TCP Client & Java TCP Server
here is a working code for the same:
Jserver.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Jserver{
public static void main(String args[]) throws IOException{
ServerSocket s=new ServerSocket(5000);
try{
Socket ss=s.accept();
PrintWriter pw = new PrintWriter(ss.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br1 = new BufferedReader(new InputStreamReader(ss.getInputStream()));
//String str[20];
//String msg[20];
System.out.println("Client connected..");
while(true)
{
System.out.println("Enter command:");
pw.println(br.readLine());
//System.out.println(br1.readLine());
}
}
finally{}
}
}
Client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000 # Reserve a port for your service.
s.connect((host, port))
while 1:
print s.recv(5000)
s.send("message processed.."+'\n')
s.close
I know it is late but specifically for your case I would recommend RabbitMQ RPC calls. They have a lot of examples on their web in Python, Java and other languages:
https://www.rabbitmq.com/tutorials/tutorial-six-java.html
for the people who are struggling with,
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
your can also use
.encode() to send the data

Categories

Resources