PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label client. Show all posts
Showing posts with label client. Show all posts

Saturday, October 22, 2022

[FIXED] Why am I getting a bad file descriptor error?

 October 22, 2022     c++, client, sockets     No comments   

Issue

I am trying to write a short program that acts like a client, like telnet. I receive from the user input like so: www.google.com 80 (the port number) and /index.html However, I get some errors. When I write some debug information, it says that I have a bad file descriptor and Read Failed on file descriptor 100 messagesize = 0.

struct hostent * pHostInfo;
struct sockaddr_in Address;
long nHostAddress;
char pBuffer[BUFFER_SIZE];
unsigned nReadAmount;
int nHostPort = atoi(port);

vector<char *> headerLines;
char buffer[MAX_MSG_SZ];
char contentType[MAX_MSG_SZ];

int hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (hSocket == SOCKET_ERROR)
{
  cout << "\nCould Not Make a Socket!\n" << endl;
  return 1;
}
pHostInfo = gethostbyname(strHostName);
memcpy(&nHostAddress,pHostInfo -> h_addr, pHostInfo -> h_length);

Address.sin_addr.s_addr = nHostAddress;
Address.sin_port=htons(nHostPort);
Address.sin_family = AF_INET;

if (connect(hSocket, (struct sockaddr *)&Address, sizeof(Address)) == SOCKET_ERROR)
{
  cout << "Could not connect to the host!" << endl;
  exit(1);
}
char get[] = "GET ";
char http[] = " HTTP/1.0\r\nHost: ";
char end[] = "\r\n\r\n";
strcat(get, URI);
strcat(get, http);
strcat(get, strHostName);
strcat(get, end);
strcpy(pBuffer, get);
int len = strlen(pBuffer);
send(hSocket, pBuffer, len, 0);
nReadAmount = recv(hSocket,pBuffer, BUFFER_SIZE, 0);
//Parsing of data here, then close socket
if (close(hSocket) == SOCKET_ERROR)
{
  cout << "Could not close the socket!" << endl;
  exit(1);
} 

Thanks!


Solution

You have a buffer overrun in your code. You're attempting to allocate a bunch of character arrays together into a buffer than is only 5 bytes long:

char get[] = "GET ";  // 'get' is 5 bytes long
char http[] = " HTTP/1.0\r\nHost: ";
char end[] = "\r\n\r\n";
strcat(get, URI);  // BOOM!
strcat(get, http);
strcat(get, strHostName);
strcat(get, end);

This is likely overwriting your local variable hSocket, resulting in the "bad file descriptor error".

Since you're using C++ (you have a vector in your code), just use a std::string instead of C arrays of characters so that you don't have to worry about memory management.



Answered By - Adam Rosenfield
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to send strings between python and go

 October 22, 2022     client, go, python, server, sockets     No comments   

Issue

I am trying to understand how to interact with python socket server meant for python socket client but in go

please rewrite python client in go language with same functionality without changing server code, that should be enough for me to understand how to do it

server:

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = '127.0.0.1'
port = 5556

server.bind((host,port))
server.listen()
client, adress = server.accept()
#1
variable1 = client.recv(4096).decode('utf-8')
print(variable1)
#2
client.send("send2".encode('utf-8'))
#3
variable2 = client.recv(4096).decode('utf-8')
print(variable2)
#4
client.send("send4".encode('utf-8'))

client:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = '127.0.0.1'
port = 5556

client.connect((host, port))


#1
client.send("send1".encode('utf-8'))
#2
variable1 = client.recv(4096).decode('utf-8')
print(variable1)
#3
client.send("send3".encode('utf-8'))
#4
variable2 = client.recv(4096).decode('utf-8')
print(variable2)

Solution

Close the connection to terminate the stream of data from the server to the client:

⋮
client.send("text1".encode('utf-8'))
client.close()

Read to EOF in the client program:

⋮
message, err := io.ReadAll(conn)                
checkError(err)
fmt.Println(string(message))


Answered By - gopher
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to send multiple of asynchronous requests from client to server

 October 22, 2022     asynchronous, client, java, server, sockets     No comments   

Issue

I've built simple client-server model using sockets. The server receives 1 type of request: 2 numbers from client, sums them, waits for 5 seconds and sends the response back to the client. I'm trying to send 20 asynchronous request from the client without waiting for response. The client should sums all the numbers from all the 20 Reponses from server. I'm trying to understand what should I use and how? Threads on the server, or the client and how? I've added my client and server classes. Server:

public  class Server {
    public static void main(String[] args) throws IOException {
        try {
            //Make a ServerSocket to listen for message
            ServerSocket ss = new ServerSocket(7777);

            while (true == true) {
                //Accept input from socket
                Socket s = ss.accept();

                //Read input from socket
                InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                String message = reader.readLine();
                System.out.println(message);
                //parse the json recieved from client and sum the 2 numbers
                Object obj = new JSONParser().parse(String.valueOf(message));
                JSONObject jo = (JSONObject) obj;
                long num1 = (long) jo.get("num1");
                long num2 = (long) jo.get("num2");
                long sum = num1 + num2;
                Thread.sleep(5000);

                //putting response as json
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("response", sum);
                //get the message and write it to the socket as response
                PrintWriter writer = new PrintWriter(s.getOutputStream());
                writer.println(jsonResponse);
                //System.out.println(df);
                writer.close();
            }
        } catch (IOException | ParseException | InterruptedException ex) {
            System.out.println(ex);
        }
    }
}

Client:

public  class Client {
    public static void main(String[] args) throws IOException {
        try {
            //this variable will sum all the responses from server
            long sumOfAllResponses = 0;
            
            for(int i = 0 ; i< 20; i++){
                //Create a Socket with ip and port number
                Socket s = new Socket("localhost", 7777);
                Scanner in = new Scanner(System.in);
                PrintWriter writer = new PrintWriter(s.getOutputStream());
                InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                //Creating json with 2 numbers to be sent to server as a request
                JSONObject jsonRequest = new JSONObject();
                jsonRequest.put("num1", 1);
                jsonRequest.put("num2", 1);
                System.out.println(jsonRequest);
                //Make a printWriter and write the message to the socket
                writer.println(jsonRequest);
                writer.flush();
                //Get the response message from server
                String responseMessage = reader.readLine();
                //parse the response and add the result to the sum variable
                Object obj = new JSONParser().parse(String.valueOf(responseMessage));
                JSONObject jo = (JSONObject) obj;
                sumOfAllResponses += (long) jo.get("response");
            }
            System.out.println(sumOfAllResponses);
        }
        catch (IOException | ParseException ex) {
            ex.printStackTrace(); // (**)
        }
    }
}

Solution

Asynchronous means sending message and not waiting for response.

//Get the response message from server - so you wait whole 5 seconds for response :)
String responseMessage = reader.readLine();

The simplest solution in this case is to remove waiting for response each time. So, get rid of above lines from loop inside Client class.

In this particular client-sever case you do not need additional threads, if you would perform asynchronous things inside one application, then so. Take a look at Java Futures with some tutorial on how to use them. But if you want to get a result from server, you have to wait anyway. And you want to get results of all calcuations. Hence, you have to store all incoming requests somewhere. Simple, naive and impractical, but showing asynchronicity concept code may look like this

public class Client {
  public static void main(String[] args) throws IOException {
    try {
        long start = System.currentTimeMillis();
        BufferedReader reader = null;
        for(int i = 0 ; i < 20; i++){
            Socket s = new Socket("localhost", 7777);
            PrintWriter writer = new PrintWriter(s.getOutputStream());
            InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
            reader = new BufferedReader(streamReader);
            // just make sure you send data and do not wait for response
            System.out.println("Sending " + i  + " : " + (System.currentTimeMillis() - start)); 
            writer.println(i);
            writer.flush();
        }
        //this line works like future.get(), it hangs client until it receives result
        String responseMessage = reader.readLine();
        // process returned data as you want
        System.out.println(responseMessage);
    }
    catch (IOException ex) {
        ex.printStackTrace(); // (**)
    }
  }
}

public class Server {
  public static void main(String[] args) throws IOException {
    try {
        //Make a ServerSocket to listen for message
        ServerSocket ss = new ServerSocket(7777);
        Socket s;
        //we need to store incoming requests to process, and return them
        List<String> integerList = new LinkedList<>();

        while (true) {
            s = ss.accept();

            InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);
            String message = reader.readLine();
            System.out.println(message);
            // do something here
            
            Thread.sleep(5000);

            PrintWriter writer = new PrintWriter(s.getOutputStream());
            integerList.add(message);
            writer.println(integerList);
            writer.close();
        }
    } catch (IOException | InterruptedException ex) {
        System.out.println(ex);
    }
  }
}


Answered By - R-tooR
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 19, 2022

[FIXED] What is the opposite of an API Endpoint

 September 19, 2022     api, client, consumer, endpoint, service     No comments   

Issue

When talking about a service layer, I might talk about adding an Endpoint to a service. ...but when I want to talk about the corresponding consumer of that specific endpoint I would want to talk about the Client's "Invoker"?

Feels like there should be a term for this and it's been bugging me for days.


Solution

Are you maybe thinking of an API call? Like what a user uses to get access to the endpoint?



Answered By - wvarner
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 15, 2022

[FIXED] How to print while waiting for input?

 September 15, 2022     client, multithreading, printing, python     No comments   

Issue

def receivedata(self):
    while True:
        data = self.soc.recv(1024)
        if data != "" or data != '' or data != "":
            sys.stdout.write("Recv>> ")
            sys.stdout.write(data)
            sys.stdout.flush()
            if data == "Server Shutdown":
                self.soc.close()
        elif not data:
            continue
def senddata(self):
    while True:
        try:
            sys.stdout.write("Send>> ")
            msg = sys.stdin.readline()
            self.soc.send(msg)
        except socket.error:
            sys.stdout.write("Socket Connection Timed Out")

This is part of my client code of python, and what I expect from this is while this waits for user input, it prints what it receives from server.

However, client does not print anything when it is waiting for user input — it only prints when something has been entered by user.

Is there a way that I could change this so that it prints even when it is waiting for user input?


Solution

If your program needs to wait on 2 separate events (user input and incoming socket data), you'll have to use threads, something like:

recv_thread = threading.Thread(target=receivedata)
recv_thread.setDaemon(True)
recv_thread.start()
senddata()

Couple of things about the code:

  • when socket.error is encountered it can be something other than timeout.
  • at one point you will need to exit the while loop from senddata (when the user input a certain text? or) in case of exception.
  • also add exception handling in receivedata
  • if statement in receivedata is not OK. you could replace it to:

    if data:
        ...if statements...
    


Answered By - CristiFati
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 12, 2022

[FIXED] How to not cache server worker client

 July 12, 2022     caching, client, message, service-worker     No comments   

Issue

I've a webpage that sends a message to a service worker script. To be able to do this, the webpage needs to be a client of the server worker script. There are different methods to do this, but as far as I know all methods results in that client webpages are cached in the service worker.

I was wondering if it's possible that a webpage can send messages to a server worker script, withouth it having to be cached to the server worker?


Solution

Sure—there's no requirement that a service worker cache anything at all, or even that a service worker implement a fetch handler and intercept network requests. You could create a service worker that just has a message handler that listens for incoming messages from the pages it controls:

// service-worker.js:
self.addEventListener('message', event => {
  // Do something with event.data
});

But if you're just using a service worker to listen for messages, and not intercept network requests, I wonder whether an alternative like a SharedWorker or just a plain-vanilla Worker would be a better alternative?



Answered By - Jeff Posnick
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] How to increase message size in grpc using python

 July 10, 2022     client, grpc, message, python, server     No comments   

Issue

I am using grpc for message passing and am testing a simple server and client. When my message size goes over the limit, I get this error.

grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with 
(StatusCode.INVALID_ARGUMENT,
 Received message larger than max (7309898 vs. 4194304))>

How do I increase the message size on the server and client side?


Solution

Changing the message_length for both send and receive will do the trick.

channel = grpc.insecure_channel(
    'localhost:50051',
    options=[
        ('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),
        ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH),
    ],
)


Answered By - Dumbo
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing