C#套接字错误,无法发送套接字未连接?

时间:2015-02-10 19:12:23

标签: c# .net sockets

我正试图掌握套接字并证明它比我想象的要困难一些。我已经用Google搜索了这个错误,并试图通过玩弄我的代码来解决它,但我不明白这里有什么不对。以下代码给出了一个套接字异常,错误"由于没有连接套接字而且(当使用sendto调用在数据报套接字上发送时)没有提供发送或接收数据的请求,因此没有提供地址。 #34;正如您所看到的,我在本地计算机上尝试此操作,客户端只需连接并发送一个字符串。任何提示或指示都会很好!

注意我已经在Stack Overflow上阅读了其他类似的问题,但还没有设法用解决方案修复我的程序!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Server
{
    class Program
    {
        private static Socket socket = null;
        private static Socket client = null;
        private static IPAddress ipAddress = null;
        private static int port = 1090;
        private static IPEndPoint endPoint = null;
        private static byte[] buffer;
        private static int socketRecv = 0;

        static void Main(string[] args)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ipAddress = IPAddress.Parse(GetLocalIPv4(NetworkInterfaceType.Ethernet));
            endPoint = new IPEndPoint(ipAddress, port);
            buffer = new byte[1024];

            Console.WriteLine("\nVariables initialized...");

            socket.Bind(endPoint);
            socket.Listen(5);

            Console.WriteLine("\nSocket bound and listening...");

            client = socket.Accept();

            Console.WriteLine("\nSocket accepted connection...");
            //the program gets to here, then the exception is thrown

            while (true)
            {
                if (socketRecv == 0)
                {
                    socketRecv = socket.Receive(buffer);
                    continue;
                }
                Console.WriteLine("\nData wrote...\n");
                break;
            }

            Console.WriteLine(System.Text.Encoding.Default.GetString(buffer));
            Console.Read();

        }

        public static string GetLocalIPv4(NetworkInterfaceType _type)
        {
            string output = "";
            foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
                {
                    foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            output = ip.Address.ToString();
                        }
                    }
                }
            }
            return output;
        }
    }
}

0 个答案:

没有答案