請教bcb udp socket通信例子

david0620 2009-03-20 11:41:25
哪位有udp socket通信的例子。
bcb的.
...全文
1232 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zz997788 2009-04-10
  • 打赏
  • 举报
回复
可用bcb自带的fastnet中的nmudp,很简单好用呢。
我不懂电脑 2009-03-20
  • 打赏
  • 举报
回复
udp是跨语言的,可以用。
david0620 2009-03-20
  • 打赏
  • 举报
回复
我的服務器是用.net寫的程式,是用udp的
客戶端是用bcb寫的程式,也想要udp這個東西
所以請問大家有什麼的建於沒?
BORLANDSUN 2009-03-20
  • 打赏
  • 举报
回复
BCB自带的UDP Socket有问题,建议使用Indy组件栏中的Indy UDP Socket,非常好用.
controstr 2009-03-20
  • 打赏
  • 举报
回复
BCB有自带的一个UDPSocket控件
如果你要使用SOCKET自己写一个代码如下


// 接收消息
int ReadFrom(char FAR * cp, unsigned short &nPort, char FAR * pBuf, unsigned int len)
{
// addr用于取得客户端的地址信息
SOCKADDR_IN addr;
int nLen = sizeof(addr);

int currlen = 0;
if ( len > 0 )
{
int bytes = ::recvfrom( m_hSocket, pBuf, len, 0, (struct sockaddr*)&addr, &nLen );
if ( bytes > 0 )
{
currlen += bytes;
char * p = inet_ntoa(addr.sin_addr);
memcpy(cp, p, strlen(p));
cp[strlen(p)] = 0;
//strcat(cp, p);
nPort = ntohs(addr.sin_port);
// 缓存中没有数据
#ifdef WIN32
}else if ( bytes < 0 && ::WSAGetLastError() != WSAEWOULDBLOCK )
{
; // break;
#else // linux or unix
}else if ( bytes < 0 && (errno == EWOULDBLOCK || errno == EAGAIN) )
{
;// break;
#endif
}else if ( bytes < 0 ) // 套接字错误
{
return -1;
}else if ( bytes == 0 ) // 连接已断开
{
return 0;
}
}
*(pBuf+currlen) = 0;
++currlen;
return currlen;
}

// 发送消息
int SendTo(const char FAR * cp, const unsigned short nPort, const char FAR * pBuf, unsigned int len)
{
struct sockaddr_in addr;
memset( &addr, 0x0, sizeof(addr));

addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = ::inet_addr( cp );

if ( addr.sin_addr.S_un.S_addr == -1 )
{
struct hostent *pHost;
pHost = gethostbyname(cp);
if ( pHost != NULL )
{
if (pHost->h_addr == NULL )
return false;
addr.sin_addr.S_un.S_addr = ((struct in_addr*)pHost->h_addr_list[0])->S_un.S_addr;
}else
return false;
}
addr.sin_port = ::htons(nPort);

unsigned int portion_size = 0, send_size = 0;
while ( send_size < len ) // 如果发送的数据大小和实际需要发送的大小不同,则认为出现例外
{
portion_size = len - send_size;
if ( portion_size > 32768 )
portion_size = 32768;
// 发送数据
int bytes = ::sendto( m_hSocket, pBuf + send_size, portion_size, 0, (sockaddr*)&addr, sizeof(addr) );
// 当出现与Nonblocking模式有关的错误时
#ifdef EAGAIN
if ( error == EAGAIN )
return 0;
#endif
#ifdef EWOULDBLOCK
if ( error == EWOULDBLOCK )
return 0;
#endif
if ( bytes > 0 )
{
send_size += bytes;
}else if ( bytes < 0 )
{
return -1;
}else
return 0;
}
return send_size;
}

1,317

社区成员

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

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