我有问题。为什么我的客户端无法从服务器接收数据?服务器正在从客户端接收数据而不会出现问题。是因为我的客户端没有连接到我的服务器客户端上。有人知道吗?抱歉我的英语,我来自捷克共和国。 :)
这是我的UDP客户端:
UdpClient client;
public IPAddress serverIP = IPAddress.Parse("127.0.0.1");
public Form1()
{
InitializeComponent();
client = new UdpClient();
}
public void SendData()
{
client.Connect(serverIP, 3000);
byte[] data = Encoding.ASCII.GetBytes("Hi, I'm new client.");
client.Send(data, data.Length);
DoListening();
}
public void DoListening()
{
IPEndPoint adress = new IPEndPoint(serverIP, 3000);
byte[] receivedbytes = client.Receive(ref adress);
string recieved = Encoding.ASCII.GetString(receivedbytes);
MessageBox.Show("Recieved: " + recieved);
}
private void button1_Click(object sender, EventArgs e)
{
SendData();
}
这是我的UDP服务器:
public Form1()
{
InitializeComponent();
Thread listening = new Thread(new ThreadStart(DoListening));
listening.Start();
}
public void ClientThread(Object adress)
{
IPEndPoint ip = adress as IPEndPoint;
UdpClient client = new UdpClient();
client.Connect(ip);
byte[] data = Encoding.ASCII.GetBytes("No nazdar");
client.Send(data, data.Length);
MessageBox.Show("Sending data..");
}
public void DoListening()
{
while (true)
{
UdpClient client = null;
client = new UdpClient(3000);
IPEndPoint host = new IPEndPoint(IPAddress.Any, 0);
MessageBox.Show("Listening");
byte[] receivedbytes = client.Receive(ref host);
string recieved = Encoding.ASCII.GetString(receivedbytes);
MessageBox.Show("Client " + host.Address.ToString() + " conected. Message: " + recieved);
new Thread(new ParameterizedThreadStart(ClientThread)).Start(host);
Console.WriteLine("Doslo k vyjimce z duvodu : {0}", ex.SocketErrorCode);
}
}
答案 0 :(得分:0)
不确定,但我认为您正在尝试连接到localhost
UdpClient client;
public IPAddress serverIP = IPAddress.Parse("127.0.0.1");
public Form1()
{
InitializeComponent();
client = new UdpClient();
}
public void SendData()
{
client.Connect(serverIP, 3000);
你正在与自己联系。您需要为实际的服务器IP地址更改127.0.0.1 ...
////我假设客户端和服务器不在同一台设备上。
答案 1 :(得分:0)
您可能喜欢route_io,它是基于c / c ++的库,它使udp / tcp / http都在一个实例中。您只需要获得源代码和示例就可以为您的项目做任何事情。简单的例子
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "route_io.h"
void init_instance(void *arg);
void read_handler(rio_request_t *req);
void init_instance(void *arg) {
printf("%s\n", "start instance");
}
void read_handler(rio_request_t *req) {
printf("preparing echo back %.*s\n", (int) (req->in_buff->end - req->in_buff->start), req->in_buff->start);
rio_write_output_buffer_l(req, req->in_buff->start, (req->in_buff->end - req->in_buff->start));
}
void on_conn_close_handler(rio_request_t *req) {
printf("%s\n", "connection closing");
}
int main(void) {
rio_instance_t * instance = rio_create_routing_instance(24, NULL, NULL);
rio_add_udp_fd(instance, 12345/*port*/, read_handler, on_conn_close_handler);
rio_add_tcp_fd(instance, 3232/*port*/, read_handler, 64, on_conn_close_handler);
rio_start(instance);
return 0;
}