请高手帮忙看看这个程序!!
这是一个用winsock传送小文件的程序,每次都可以连接成功,可就是传东西的时候出错,请高手们指点一下!!!
好像是在send和recv的时候出的错!
首先是服务器程序:
#include <winsock.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <iostream.h>
void fatal(char *string)
{
printf("%s\n", string);
exit(1);
}
#define SERVER_PORT 12345
#define BUF_SIZE 4096
#define QUEUE_SIZE 10
void main(int argc, char *argv[])
{
int b, I, sa;
char buf[BUF_SIZE];
struct sockaddr_in channel;
SOCKADDR saclnt;
int saclntlen = sizeof(saclnt);
int status;
WSADATA wsaData;
if(status = WSAStartup(MAKEWORD(1,1), &wsaData) != 0)
exit(1);
/* Build address structure to bind to socket. */
memset(&channel, 0, sizeof(channel)); /* zero channel */
channel.sin_family = AF_INET;
channel.sin_addr.s_addr = htonl(INADDR_ANY);
channel.sin_port = htons(SERVER_PORT);
/* Passive open. Wait for connection. */
SOCKET s;
s = socket(AF_INET, SOCK_STREAM, 0); /* create socket */
if (s < 0) fatal ("socket failed");
b = bind(s, (PSOCKADDR) &channel, sizeof(channel));
if (b < 0) fatal("bind failed");
I = listen(s, QUEUE_SIZE); /* specify queue size */
if (I < 0) fatal("listen failed");
sa = accept(s, &saclnt, &saclntlen);
char *p_c;
int count;
int numchr;
while (1){
p_c = buf;
count = BUF_SIZE;
numchr = 0;
do {
numchr = recv(sa,p_c,count,0);
if (numchr == SOCKET_ERROR) {
int err = WSAGetLastError();
cout << err << endl;
}
else {
p_c += numchr;
count -= numchr;
}
}while(count > 0);
cout << buf << endl;
}
}
然后是客户端程序:
#include <iostream.h>
#include <winsock.h>
#include <io.h>
#include <stdio.h>
#define SERVER_PORT 12345
#define BUF_SIZE 4096
#define ip "202.33.11.102"
void fatal(char *string)
{
printf("%s\n", string);
exit(1);
}
void main(int argc, char **argv)
{
int c, s, bytes;
char buf[BUF_SIZE] = "sadfsdf";
struct sockaddr_in channel;
int status;
WSADATA wsaData;
if(status = WSAStartup(MAKEWORD(1,1), &wsaData) != 0)
exit(1);
s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s <0) fatal ("socket");
channel.sin_family= AF_INET;
channel.sin_addr.s_addr = inet_addr(ip);
channel .sin_port= htons(SERVER_PORT);
c = connect(s, (struct sockaddr *) &channel, sizeof(channel));
if (c < 0) fatal ("connect failed");
char *p_c;
int count;
int numchr;
p_c = buf;
count = BUF_SIZE;
numchr = 0;
do {
numchr = send (s,p_c,count,0);
if (numchr == SOCKET_ERROR){
int err = WSAGetLastError();
cout << err << endl;
}
else {
p_c += numchr;
count -= numchr;
}
}while(count > 0);
}