插座程序添加整数在C [英] socket program to add integers in c

查看:180
本文介绍了插座程序添加整数在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何一个可以请告诉我怎么才能发送整数从客户端到服务器并将它们添加
  在C

Can any one please tell me how can we send integers from client to server and add them in c.

我是能够成功地发送字符串,但我无法弄清楚如何发送
  整数。

I was able to send strings successfully but i am not able to figure out how to send integers.

请帮助我!下面写code是阅读的字符串。我能怎样改变
  它读取并添加整数。

Please help me out!! The below written code was for reading strings. How can i change it it to read and add integers.

#define SOCK_PATH "echo_socket"

int main(void)
{

 int s, t, len;
 struct sockaddr_un remote;
 char str[100];
 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
 perror("socket");
 exit(1);
}

 printf("Trying to connect...\n");
 remote.sun_family = AF_UNIX;
 strcpy(remote.sun_path, SOCK_PATH);
 len = strlen(remote.sun_path) + sizeof(remote.sun_family);


 int val=connect(s, (struct sockaddr *)&remote, len);

 if ( val< 0) {
 perror("connect");
 exit(1);
 }

 printf("Connected.\n");

 printf("ENTER THE NUMBERS:");

while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {

if (send(s, str, strlen(str), 0) == -1) {
perror("send");
exit(1);
}
if ((t=recv(s, str, 100, 0)) > 0) {
str[t] = '\0';
 printf("echo> %s", str);
} else 
{
  if (t < 0) perror("recv");
  else printf("Server closed connection\n");
  exit(1);
 }

}

推荐答案

简单:

int my_int = 1234;
send(socket, &my_int, sizeof(my_int), 0);

以上code发送的整数的正如的在插座上。接收它的另一面:

The above code sends the integer as is over the socket. To receive it on the other side:

int my_int;
recv(socket, &my_int, sizeof(my_int), 0);

不过,要小心,如果这两个程序在具有不同字节顺序系统上运行。

However, be careful if the two programs runs on systems with different byte order.

编辑:如果您担心平台兼容性,字节顺序和这样的,那么所有的数据转换为字符串的一端,然后再转换回来,另一方面,可能是最好的选择。例如参见答案从cnicutar。

If you worry about platform compatibilities, byte ordering and such, then converting all data to strings on one end and then convert it back on the other, might be the best choice. See e.g. the answer from cnicutar.

这篇关于插座程序添加整数在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆