谁有c++builder的网络、数据库 多线程编程资料,源代码??

sensing 2002-10-30 11:35:43
...全文
55 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
warton 2002-10-30
  • 打赏
  • 举报
回复
关键部分:
开始线程

if (_beginthread(TCP_Echo, STKSIZE, (void*)ssock) <0)
{
printf( "启动新线程失败!\n ");
return -1;
}



_endthread();
// return 0;
break;
warton 2002-10-30
  • 打赏
  • 举报
回复
看我的代码,socket api,多线程:


#define WSVERS MAKEWORD(2, 0)
#define STKSIZE 16536

#include <stdio.h >
#include <winsock2.h >
#include <process.h >

int TCP_Echo(SOCKET,struct sockaddr_in);

int main()
{
struct sockaddr_in fsin, sin;
SOCKET msock, ssock;
struct hostent *hostname;
unsigned short port = 10000;
int alen;
WSADATA wsadata;


if (WSAStartup(WSVERS, &wsadata) != 0)
{
printf( "调用winsock.dll失败! ");
return -1;
}

memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr =inet_addr( "192.168.4.142 "); //
sin.sin_port = htons(port);

msock = socket(PF_INET, SOCK_STREAM, 0);
if (msock == INVALID_SOCKET)
{
printf( "create socket error\n ");
return -1;
}

if (bind(msock, (struct sockaddr *)&sin, sizeof(sin))==SOCKET_ERROR)
{
printf( "bind error\n ");
return -1;
}

if (listen(msock, 5)==SOCKET_ERROR)
{
printf( "listen error\n ");
return -1;
}
//hostname=gethostbyaddr(inet_ntoa(sin.sin_addr),8,0);
//printf( "%s\n ",hostname- >h_name);
printf( "本地地址:%s\n ",inet_ntoa(sin.sin_addr));//
printf( "服务器监听端口:%d\n ",ntohs(sin.sin_port));


while(1)
{
alen = sizeof(struct sockaddr);
ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
if (ssock == INVALID_SOCKET)
{
printf( "accept error\n ");
return -1;
}
printf( "有客户连接自 %s\r\n ", inet_ntoa(fsin.sin_addr));
if (_beginthread(TCP_Echo, STKSIZE, (void*)ssock) <0)
{
printf( "启动新线程失败!\n ");
return -1;
}
}
}
//线程要调用的函数:处理客户发送来的数据
int TCP_Echo(SOCKET fd,struct sockaddr_in sin)
{
char buf[4096];
int cc = 0;

memset(buf, 0, sizeof(buf));
strcpy(buf, "Enter 'Q' to exit\r\n ");
if (send(fd, buf, strlen(buf), 0)==SOCKET_ERROR)
{
printf( "echo send error\n ");
return -1;
}

memset(buf, 0, sizeof(buf));
cc = recv(fd, buf, sizeof(buf), 0);
printf( "客户发送的数据:%s\n ", buf);

while(cc!=SOCKET_ERROR && cc > 0)
{
if (send(fd, buf, cc, 0)==SOCKET_ERROR)
{
printf( "echo send error\n ");
break;
}
/* if (send(fd, "\r\n ", 2, 0)==SOCKET_ERROR)
{
printf( "echo send error\n ");
break;
}*/
memset(buf, 0, sizeof(buf));
cc = recv(fd, buf, sizeof(buf), 0);
printf( "客户发送的数据:%s\n ", buf);
if (buf[0]=='Q')
{

_endthread();
// return 0;
break;
}
}
if (cc==SOCKET_ERROR)
printf( "echo recv error\n ");

closesocket(fd);
return 0;
}

1,317

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder 网络及通讯开发
社区管理员
  • 网络及通讯开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧