Client and Server PCs are not connecting within a LAN - java

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.

Related

Socket messaging between Java Client and Python Server

I try to create a Socket messager between a Java Client and Python Server. It works to send a message ("Testdata") from client to server and print it out. But after input and send a message from server to client, I get no output from client. The client 'freezes' and must be terminated.
What is the problem with my client input?
Terminal Server:
py socketServer.py
Connection from: ('127.0.0.1', 57069)
from connected user: Testdata
> Test
send data..
Terminal Client:
java socketClient
Testdata
Python-Server:
import socket
def socket_server():
host = "127.0.0.1"
port = 35100
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(2)
conn, address = server_socket.accept()
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
break
print("from connected user: " + str(data))
data = input('> ')
conn.send(data.encode())
print("send data...")
conn.close()
if __name__ == '__main__':
socket_server()
Java-Client:
private static void socketTest(){
String hostname = "127.0.0.1";
int port = 35100;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, false);
BufferedReader input =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
Scanner in = new Scanner(System.in);
String text;
do {
text = in.nextLine();
writer.print(text);
writer.flush();
System.out.println("from server: " + input.readLine());
} while (!text.equals("exit"));
writer.close();
input.close();
socket.close();
}
}
This is because python messages are not explicitly finished with \r\n like #carlos palmas says in this answer.

How to send two strings through client to server using Socket in Java?

Here my code (sends only single String)
Client
Socket sock = new Socket("localhost",9999);
Scanner in = new Scanner(System.in);
String msg;
PrintStream pr = new PrintStream(sock.getOutputStream());
System.out.print("Enter the Msg : ");
msg = in.nextLine();
pr.print(msg);
Server
ServerSocket ser = new ServerSocket(9999);
Socket sock = ser.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String msg = br.readLine();
System.out.println("Received Msg : "+msg);
This Code Works Clearly. But I want to Send two strings through client to server.

socket.recv not working with non blocking

this is my python code.
Whenever i tries to send it a string it does not receive and times out after 10 seconds.
python server
import socket # Import socket module
import sys
import select
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 50001 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
a = []
b = []
s.listen(1) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
s.setblocking(0)
ready = select.select([s], [s], [s], 10)
while True:
if ready[0]:
data = s.recv(4096)
print data
print "reached"
print 'Got connection from', addr
c.send('Thank you for connecting \r\n') #all strings have to end with /r/n!!!
print "sent"
break;
c.close() # Close the connection
My Java Client
import java.net.*;
import java.io.*;
public class MTExample
{
public MTExample()
{
String sentence;
String modifiedSentence = "undefined";
try
{
//ceating the socket to connect to server running on same machine binded on port no 3000
Socket client = new Socket("127.0.0.1", 50001);
System.out.println("Client connected ");
//getting the o/p stream of that connection
PrintStream out = new PrintStream(client.getOutputStream());
//sending the message to server
System.out.print("Hello from client\n");
System.out.flush();
//reading the response using input stream
//BufferedReader in= new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//System.out.println(in.readLine());
//closing the streams
sentence = in.readLine();
sentence = "haha";
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
outToServer.writeBytes(sentence + "\n");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
System.out.println("FROM SERVER: " + modifiedSentence);
client.close();
in.close();
out.close();
}
catch(Exception err)
{
System.err.println("hi* err"+err);
}
}
public static void main(String a[])
{
new MTExample();
}
}
Is there something wrong with the non blocking method in Python? the Java client was working fine before i changed the blocking segement on python to be non blocking on the recv socket

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.

server client socket programming output difficulties

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.

Categories

Resources