Initially I would like to thank you for your time...
I created a server socket in c++ in my macbook and a client/socket using Java in a diffrent machine which runs windows xp. I have specified the port to 5000 but I cant specify the correct Host and thus I can not make the connection. When I created a c++ server/socket in windows xp using WinSock2 the connection was made perfectly as I used the localhost...any ideas???
Thnx in advance
C++ code
int main( int argc, const char** argv )
{
/* SOCKET VARIABLES */
int sock;
struct sockaddr_in server;
int mysock;
char buff[1024];
int rval;
/*CREATE SOCKET*/
sock =socket(AF_INET, SOCK_STREAM, 0);
if (sock<0)
{
perror("*FAILED TO CREATE SOCKET*");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=5000;
/*CALL BIND*/
if (bind(sock, (struct sockaddr *)&server, sizeof(server)))
{
perror("BIND FAILED");
exit(1);
}
/*LISTEN*/
listen(sock, 5);
/*ACCEPT*/
do{
mysock= accept(sock, (struct sockaddr *) 0, 0);
if (mysock==-1)
{
perror ("ACCEPT FAILED");
}
else
{
memset(buff, 0, sizeof(buff));
if ((rval=recv(mysock, buff, sizeof(buff), 0)) <0) {
perror("READING STREAM MESSAGE ERROR");
}
else if(rval==0)
printf("Ending connection");
else
printf("MSG: %s\n", buff);
printf("GOT THE MESSAGE (rval = %d)\n", rval);
}
return 0;
}while (1) ;
Java code
import java.io.;
import java.net.;
public class SOK_1_CLIENT {
public void run() throws Exception
{
Socket SOCK =new Socket ("localhost",5000);
PrintStream PS =new PrintStream(SOCK.getOutputStream());
PS.println("HELLO TO SERVER FROM CLIENT");
InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE =BR.readLine();
System.out.println(MESSAGE + "java");
}
}
In java client, use the IP address of the system which is running server not "localhost". Localhost will refer to the local loopback address of the machine running the client code which is 127.0.0.1, but you have your server running on different machine, hence connection is not possible:
public void run() throws Exception
{
String address = "address_of_machine_running_server";
Socket SOCK =new Socket (address,5000);
PrintStream PS =new PrintStream(SOCK.getOutputStream());
PS.println("HELLO TO SERVER FROM CLIENT");
InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE =BR.readLine();
System.out.println(MESSAGE + "java");
}
Also note that you need to set the firewall accordingly to allow the connections.
allow incoming and outgoing connections in both machine
check if ip address of your server is correct
try pinging the host(server) with its ip address to make sure that its up and working
if all the above returns positive, you will a have sucessfull connection.
Related
My assignment requiers me to write an server in c but client in java. I need to send some integer to my client as instructions. They can connected smoothly but my java client cannot Receive the integer send from c server. there is only two possibilities: my c server did not send the Number out OR my client does not Receive the integer correctly. The c server is able to loop as I type in since the printf and scanf is executed while nothing happends on the client side.
I am stuck here, any help will be appreciate!
=========================================================================
UPDATE:
I correct the main class in java where the class name of the client into dotClient, and my client was able to conncected and read the inputs from the server.
I have try to send an 'int' directly in the server side, but When the client(java) use DataInputStream.ReadInt(), it returns a randomly big number as if the size of int in c and size of int in java is not matched.When I use a c client to do the same job, it works normal. So there is Hidden Problem for using dataInputStream directly with a c server, as I tried readShort() and ReadLong() as well.
As suggested, I use bufferReader.
And send string in server side, and perse it into int in client.
it works.
hère is my updated c code
#define PORT 55555
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024];
int returnSend = 0;
// Creating socket file descriptor
if (
(server_fd = socket(AF_INET, SOCK_STREAM, 0))
== 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
printf("%s\n", "Socket created!");
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET,
SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
printf("Socket attached!\n");
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd,
(struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("socket binded!\n");
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
printf("socket listened!\n");
if ((new_socket = accept(server_fd,
(struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}// Socket formulated !
do{
fgets(buffer, sizeof(buffer), stdin);
returnSend = write(new_socket , buffer , strlen(buffer));
printf("Sending: %sReturn returnSend: %d.\n", buffer,returnSend);
} while (1);
return 0;
}
hère is my updated java client
import java.net.*;
import java.io.*;
public class dotClient
{
// initialize socket and input output streams
private Socket echoSocket= null;
private BufferedReader input = null;
// constructor to put ip address and port
public dotClient(String address, int port)
{
// establish a connection
try
{
echoSocket = new Socket(address, port);
System.out.println("Connected");
input =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
}
catch(UnknownHostException u)
{
System.out.println("exception 1: "+u);
}
catch(IOException i)
{
System.out.println("exception 2: "+i);
}
int number = 0;
String line = "";
// keep reading until read neagaive integer
try
{
while ((line = input.readLine()) != null)
{
number = Integer.parseInt(line);
System.out.println("String is :"+line);
System.out.println("number is :"+number);
}
}
catch(IOException i)
{
System.out.println("Exception 3: "+i);
}
// close the connection
try
{
input.close();
out.close();
echoSocket.close();
System.out.println("Connection closed!");
}
catch(IOException i)
{
System.out.println("Exception 4: "+i);
}
}
public static void main(String args[])
{
dotClient client = new dotClient("192.168.0.3", 55555);
}
}
In your main method you are creating a Client instance but your class is called dotClient. You might want to ensure you are creating an instance of your class dotClient. Otherwise I agree with the previous comments and would suggest BufferedReader and BufferedWriter/PrintWriter for the IO.
Do any of your try blocks catch an exception on the client? Check the return value of send(new_socket , &number , size(number) , 0 ); on the server to make sure the data was actually sent for more info checkout http://man7.org/linux/man-pages/man2/send.2.html.
I have a client implemented in Java, and a server implemented in client.
The client sends a message (string) such as "nesting:1:2" to the server, the server decodes the meaning of the input to create and send back binary data to the client.
This is the Python server code.
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
# self.data has the data
(name, index, n) = self.data.split(":")
m = int(n)
i = int(index)
size = sizes.sizes[name][i]
# creates the binary data
bf = [0x41] * size * m
key = ''.join(chr(x) for x in bf)
self.request.send(key) #
if __name__ == "__main__":
HOST = socket.gethostbyname(socket.gethostname())
PORT = 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
The client Python code is as follows:
af, socktype, proto. canonname, sa = res
s = socket(af, socktype, proto)
s.connect(sa)
s.sendall('nostring:1:5')
data = s.recv(1024)
s.close()
I tried to find the equivalent to the s.recv() method, I found read() method. So, I tried this method where byte[] buffer = new byte[157*10]; is declared outside the method.
public byte[] receive() throws IOException {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVER_PORT);
in = socket.getInputStream();
in.read(buffer);
in.close();
socket.close();
return this.buffer;
}
The issue is that the in.read(buffer) never returns until the server disconnects.
What might be wrong? This is the full source code for the client.
I didn't try, but to my mind, the socket should not be closed between the send and receive action, one socket means one connection to the server.
The python server will most likely try to answer on the given socket, which will be closed, and the java client will wait on another.
Try something like that: creating the socket in the constructor and closing it at the end of the receive (if you are sure you might call the send/receive pair only one time)
import java.net.*;
import java.io.*;
class GpcSocket {
private Socket socket;
// default value
private int SERVER_PORT = 9999;
private String SERVER_IP = "192.168.3.100";
OutputStream out = null;
InputStream in = null;
byte[] buffer = new byte[157*10];
public GpcSocket(String serverIP, int serverPort) {
this.SERVER_PORT = serverPort;
this.SERVER_IP = serverIP;
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVER_PORT);
}
public int send(byte[] str) throws IOException {
out = socket.getOutputStream();
out.write(str);
out.flush();
// out.close();
return str.length;
}
public byte[] receive() throws IOException {
in = socket.getInputStream();
in.read(buffer);
in.close();
socket.close()
return this.buffer;
}
}
I couldn't find anything about this quite specific problem, but maybe someone else has done this.
I have a server program written in C (error checking removed for readability):
int main(int arc, char *argv[])
{
int sockfd, newsockfd, portnum, cli_len, num_chars, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
// Set up the socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Set up our variables
bzero((char *) &serv_addr, sizeof(serv_addr));
portnum = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portnum); // Convert from host port to network port
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("Socket could not be bound");
listen(sockfd, 5); // Get ready to receive connections
cli_len = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &cli_len);
// Message processing
return 0;
}
Meanwhile, I have the Android client (Version 4.1.2):
private class ClientTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
InetAddress a = InetAddress.getByAddress(new byte[] {(byte) 192, (byte) 168, 1, (byte) 102});
sock = new Socket(a, 65053);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
// Message processing
} catch (UnknownHostException e) {
System.out.println("No address found for ");
} catch (IOException e) {
System.out.println("Failed to open socket");
}
return null;
}
}
The issue I have is that the socket can't be opened by the Android client. I always get "Failed to open socket" after the timeout. The android client works with a java server I have, and a java client I have at least makes the connection with the C server. I don't understand what could be wrong...
If you need more details or additional code, let me know.
You don't specify if you're running both devices (server and client) just under the same LAN, in which case you can discard connectivity problems. If not, this might be a test. If you're able to connect your client to your server under the same router, that means that otherwise (i.e., using your public IPs) there's something blocking it, probably your router. Another issues could be antiviruses, OS ports blocking, router ports blocking...
If you're not able to connect both either under the same router connection, definitely it's a code issue. As you don't know where the culprit is, I'd suggest putting several Log.d() lines within the client code and printf() statements within the server code in the connectivity snippets on both sides and see where the bottleneck is, or use some debugging tool and put some breakpoints.
---- EDIT ----
Try connecting this way:
Socket socket;
final String host = "192.168.1.X";
final int port = 65053;
final int timeout = 30000; // 30 seconds
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("Sock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("Sock", "After a reasonable amount of time, I'm not able to connect!");
}
catch (IOException ioe) {
Log.e("Sock", "Hmmm... Sudden disconnection, probably you should start again!");
}
Whelp, it was a firewall issue, embarrassingly enough. Apparently Eclipse was let through my firewall, which is why the Java server worked, but I must've missed the prompt when I ran my C code through the command line. I disabled my firewall and it worked immediately.
I've very new to networking and using networks to send messages through programming. Anyways, I have a client and server java command line application (server is running in a VM on the same machine with a bridged network adapter, and host to guest pinging works and vice versa), and it would appear on the server side that each message it receives is coming from a different port. Is this normal behavior? What happens when the machine runs out of ports to use? Does Java's libraries intelligently close the ports after it's done with them?
So basically, is this even a problem? If it is, how do I go about fixing it? Output from the server and then code for the client listed below.
SERVER OUTPUT AFTER SENDING SOME MESSAGES:
Received (/192.168.1.122:59628): shsfh
Received (/192.168.1.122:59629): dfsh
Received (/192.168.1.122:59631): dfh
Received (/192.168.1.122:59632): fdshdf
Received (/192.168.1.122:59633): shf
Received (/192.168.1.122:59637): fgfggsdfhsfdh
Received (/192.168.1.122:59638): fdshf
Received (/192.168.1.122:59639): hs
Received (/192.168.1.122:59640): hfh
CODE FOR THE CLIENT THAT SENT THOSE MESSAGES:
import java.io.*;
import java.util.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{ Scanner scan = new Scanner(System.in);
while (true)
{
String msgcont = scan.nextLine();
System.out.println(tcpSend("192.168.1.153", 6789, 5000, msgcont));
}
}
public static String tcpSend(String ip, int port, int timeout, String content)
{
String ipaddress = ip;
int portnumber = port;
String sentence;
String modifiedSentence;
Socket clientSocket;
try
{
clientSocket = new Socket(ipaddress, portnumber);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(content + '\n');
clientSocket.setSoTimeout(timeout);
modifiedSentence = inFromServer.readLine();
clientSocket.close();
outToServer.close();
inFromServer.close();
}
catch (Exception exc)
{
modifiedSentence = "";
}
return modifiedSentence;
}
}
Yes, everytime you open a socket to other host, the connection can be initiated from any of the remaining port on your machine. The OS chooses the next available port and makes the connection.
There are 65536 open ports available from which first 1-1024 ports are reserved by the system.
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