linux 编程一般都不会直接空敲代码的,比较熟练的程序员也要经常查man page的。所以,要有信心,有恒心。从基础做起,多看书,多练习。
你说的程序其实挺简单的,写一个,比较ugly,仅给楼主练习作参考。
tcpclient.c
#include "debug.h"
int main (int argc, char *argv[])
{
int cfd;
char buf[BUFSIZE];
struct sockaddr_in addr;
int addrlen = sizeof (addr);
int data[DATALEN] = { 0 };
int recv_data[DATALEN] = { 0 };
int i, j, n, average = 0;
if (argc < 2)
{
printf ("usage : %s server_ip server_port", argv[0]);
exit (0);
}
cfd = socket (PF_INET, SOCK_STREAM, 0);
check_err ("socket", cfd);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr (argv[1]);
addr.sin_port = htons (atoi (argv[2]));
connect (cfd, (struct sockaddr *)&addr, addrlen);
check_err ("socket", cfd);
for (i = 0; i < DATALEN; i++)
data[i] = i + 50;
for (i = 0; i < DATALEN; i++)
{
sprintf (buf, "%d", data[i]);
check_err ("write", write (cfd, buf, sizeof (buf)));
}
i = j = 0;
for (i = 0; i < DATALEN && read (cfd, buf, sizeof (buf)) > 0; i++)
{
if ((n = atoi (buf)) > 100)
{
recv_data[j++] = n;
printf ("recv data : %d\n", recv_data[i]);
average += n;
}
else
break;
}
average /= j;
printf ("\naverage = %d\n", average);
close (cfd);
return 0;
}
tcpserver.c
#include "debug.h"
int main (int argc, char *argv[])
{
int ret;
int sfd;
int cfd;
char buf[BUFSIZE];
struct sockaddr_in addr;
int len = sizeof (addr);
int recv_data[DATALEN] = {0};
int i, j, n;
if (argc < 2)
{
printf ("usage : %s port\n", argv[0]);
exit (-1);
}
sfd = socket (PF_INET, SOCK_STREAM, 0);
check_err ("socket", errno);
addr.sin_family = AF_INET;
addr.sin_port = htons (atoi (argv[1]));
addr.sin_addr.s_addr = INADDR_ANY;
bind (sfd, (struct sockaddr *)&addr, len);
check_err ("bind", errno);
listen (sfd, BACKLOG);
check_err ("listen", errno);
i = j = n = 0;
if ((cfd = accept (sfd, (struct sockaddr *)&addr, &len)) > 0)
{
for (i = 0; i < DATALEN && read (cfd, buf, BUFSIZE) > 0; i++)
{
if ((n = atoi (buf)) > 100)
recv_data[j++] = n;
}
}
for (i = 0; i < j; i++)
{
sprintf (buf, "%d", recv_data[i]);
check_err ("write", write (cfd, buf, sizeof(buf)));
}
check_err ("write", write (cfd, "0", sizeof(buf)));
close (cfd);
return 0;
}
debug.h
#ifndef _DEBUG_H
#define _DEBUG_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BACKLOG 10 // for max listen fds
#define DATALEN 100
#define BUFSIZE 16
#define check_err(name, ret) \
if (ret < 0) \
{ \
perror (name); \
exit (-1); \
}
#define check_null(name, ret) \
if (if ret == NULL) \
{ \
perror (name); \
exit (-1); \
}
#endif
编译后,先运行server端,然后运行client端,可以看到server发回的数据,及平均值。
百度知道不能贴代码,排版很差,将就可以看吧,有问题追问。
这类问题不难,核心就是socket通信,你可以这样做试试:
1、先将client与server打通,例如client端发送一个数字server端可以接收
2、server端接收到后可以给client端一个回执
3、实现问题的要求
再加参考下老师的代码应该可以做到,这个跟操作系统的平台没有关系的