我正在开发Windows窗体应用程序中的套接字编程(UDP套接字)。 我按下了按钮点击socket()然后我想在其他按钮上发送一些字节click.Sendto()在我点击所需的按钮时返回0但是在另一端没有收到数据但是当我从一个调用sendto()时它在同一个应用程序中运行正常。
下面是调用socket()的函数:
int socket_create(String^* error,SOCKET *sock_fd,int port_number)
{
sockaddr_in my_addr;
*sock_fd = INVALID_SOCKET;
// Create a SOCKET for the server to listen for client connections
*sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (*sock_fd == INVALID_SOCKET)
{
this->richTextBox1->AppendText("Error at socket():"+ WSAGetLastError() + "\n");
return -1;
}
else
this->richTextBox1->AppendText("Socket succesfully opened on port number: " + port_number + "\n");
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr("192.168.1.2");
my_addr.sin_port = htons(port_number);
if (bind(*sock_fd, (SOCKADDR *) & my_addr, sizeof (my_addr)) == SOCKET_ERROR)
{
this->richTextBox1->AppendText("bind failed:" + WSAGetLastError()+ "\n");
//freeaddrinfo(result);
closesocket(*sock_fd);
return -1;
}
else
this->richTextBox1->AppendText("Bind succesful on port number:" + port_number + "\n");
return 0;
}
下面是按钮代码,它调用socket_create()来打开socket:
private: System::Void Connect_btn_Click(System::Object^ sender, System::EventArgs^ e)
{
int status = 0;
String^ error;
status = socket_create(&error, &s_8888,8888);
}
套接字描述符s_8888是全局定义的。
下面是调用sendto()的按钮代码:
private: System::Void test_btn_Click(System::Object^ sender, System::EventArgs^ e)
{
sockaddr_in their_addr;
their_addr.sin_family = AF_INET;
their_addr.sin_addr.s_addr = inet_addr(ip_address);
their_addr.sin_port = htons(8888);
int length = sizeof (their_addr);
i=sendto(s_8888 , buf , sizeof(buf), 0, (SOCKADDR *) &their_addr, length);
if(i== SOCKET_ERROR)
{
MessageBox::Show("" + WSAGetLastError());
}
richTextBox1->AppendText("" + i + "\n");
}
我无法理解为什么它表现得那样以及如何解决它?