UDP сервер (что не так?)
От: nick570 Россия  
Дата: 11.01.07 05:02
Оценка:
Написал простейший UDP сервер, на втором вызове Receive получаю SocketException "An existing connection was forcibly closed by the remote host". Как такое может быть? Сервер UDP, никаких соединений быть не может. Еще.. если убрать SendTo то все работает, но мне нужна рассылка.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace UdpTest
{
    class Program
    {
        private static string serverIP = "192.168.64.66";
        private static int serverPort = 5000;

        static void Main(string[] args)
        {
            Thread thread = new Thread(new ThreadStart(ServerThread));
            thread.Start();

            using (UdpClient client = new UdpClient())
            {
                client.Connect(serverIP, 5000);
                while (true)
                {
                    client.Send(new byte[100], 100);
                    Thread.Sleep(1000);
                }
            }
        }

        private static void ServerThread()
        {
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                socket.Bind(new IPEndPoint(0, serverPort));

                byte[] buffer = new byte[65536];
                while (true)
                {
                    int read = socket.Receive(buffer);
                    if (read > 0)
                    {
                        int sent = 0;
                        for (int i = 0; i < 10; i++)
                        {
                            int port = new Random().Next(10000, 11000);
                            EndPoint point = new IPEndPoint(IPAddress.Parse(serverIP), port);
                            sent += socket.SendTo(buffer, 0, read, SocketFlags.None, point);
                        }
                        Console.WriteLine("Received {0} bytes, sent {1} bytes", read, sent);
                    }
                }
            }
        }
    }
}
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.