【问题标题】:An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dllSystem.dll 中出现“System.Net.Sockets.SocketException”类型的未处理异常
【发布时间】:2017-10-06 21:18:20
【问题描述】:

所以我已经搜索了很多领域来寻找这个答案,但我对这个错误的作用感到困惑。每当我按下启动服务器按钮...

...我收到此错误“System.dll 中发生'System.Net.Sockets.SocketException' 类型的未处理异常”

我的代码很长,但我不知道该怎么做...

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.Net.Sockets;

using System.IO;
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private  bool isserver = false;
        public const int MAXSIZE = 10;
        public Form1()
        {
            InitializeComponent();
            clearoutput();
        }
         TcpListener tcpl = new TcpListener(IPAddress.Parse(getip()), 2546);
         List<TcpClient> clients = new List<TcpClient>();
         List<string> names = new List<string>();
         bool CommandMode = false;
         List<string> banlist = new List<string>();
        TcpClient Client = new TcpClient();
        //client setup
        private void button1_Click(object sender, EventArgs e)
        {
            try {
                Output.Text = Output.Text + "You have joined as a client";



                Client = new TcpClient();
                Client.Connect(IP_address.Text, 2546);
                Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
                myThread.Start(Client);
                //whenever you send a message you must include the next two lines

                //Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(name + " has joined") }, 0, 1);
                //Client.GetStream().Write(Encoding.Unicode.GetBytes(name + " has joined"), 0, Encoding.Unicode.GetByteCount(name + " has joined"));

                //the two lines above
                Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount("\\join" + getip()) }, 0, 1);
                Client.GetStream().Write(Encoding.Unicode.GetBytes("\\join" + getip()), 0, Encoding.Unicode.GetByteCount("\\join" + getip()));

            }
            catch { }
            IP_address.Visible = false;
            Join_btn.Visible = false;
            Start_btn.Visible = false;
            Output.Visible = true;
            Input.Visible = true;
            text1.Visible = true;
            text1.Visible = true;
        }
        private void clearoutput()
        {
            Output.Text = "";
        }
        //server setup---
        private void Start_btn_Click(object sender, EventArgs e)
        {
            isserver = true;
            server_IP_lbl.Text = $"Since you are a server:\nYour ip address is : "+getip();
            //if You need a new banlist make sure you click here and allow this
            Write_to_output("you are a server");
            try
            {
                StreamReader readerfrban = new StreamReader("banlist");
                readerfrban.Close();
                Write_to_output("we found a banlist \n no worries");
            }
            catch
            {
                Write_to_output("Error- could not find a banlist creating one now");

                    StreamWriter banlistmaker = new StreamWriter("banlist");
                    banlistmaker.Close();


            }


            //open banlist
            StreamReader readerforban = new StreamReader("banlist");
            string reader = "";
            //read all bans in
            do
            {
                reader = readerforban.ReadLine();
                if (reader != null)
                    banlist.Add(reader);
            } while (reader != null);

            tcpl.Start();

            //Thread AcceptSocketsThread = new Thread(AcceptSockets);
            //AcceptSocketsThread.Start();

            /* while (true)
             {
                 string Message = Console.ReadLine();

                 if (Message.StartsWith("\\Kick"))
                 {

                     Console.Clear();
                     CommandMode = true;
                     int clientID = 0;
                     foreach (TcpClient client in clients)
                     {

                         Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
                         clientID++;
                     }
                     Write_to_output("\n\n Enter the number of the person you want to kick");
                     TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
                     toRemove.Close();
                     clients.Remove(toRemove);
                     CommandMode = false;

                 }

                 else if (Message.StartsWith("\\Reset"))
                 {
                     foreach (TcpClient client in clients)
                     {
                         client.Close();
                     }
                     clients.Clear();
                     Write_to_output("KICKED EVERY BODY");
                 }
                 else if (Message.StartsWith("\\ban"))
                 {
                     Console.Clear();
                     CommandMode = true;
                     int clientID = 0;
                     foreach (TcpClient client in clients)
                     {

                         Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
                         clientID++;
                     }
                     Write_to_output("\n\n Enter the number of the person you want to kick and ban");
                     TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
                     banlist.Add(toRemove.Client.RemoteEndPoint.ToString().Split(new char[] { ':' })[0]);
                     toRemove.Close();
                     clients.Remove(toRemove);
                     CommandMode = false;

                 }
                 //starts game

                 else
                 {
                     foreach (TcpClient client in clients)
                     {
                         SendMessage(Message, client);
                     }
                 }
             }*/
            IP_address.Visible = false;
            Join_btn.Visible = false;
            Start_btn.Visible = false;
            Output.Visible = true;
            Input.Visible = true;
            text1.Visible = true;
            text1.Visible = true;
        }
        void SendMessage(string message, TcpClient reciever)
        {
            try {
                reciever.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(message) }, 0, 1);
                reciever.GetStream().Write(Encoding.Unicode.GetBytes(message), 0, Encoding.Unicode.GetByteCount(message));
            }
            catch
            {
                Write_to_output("Was unable to send to any users error code 1.0.0.0");
            }
            }
        void AcceptSockets()
        {
            while (true)
            {
                TcpClient client = tcpl.AcceptTcpClient();
                Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
                clients.Add(client);
                myThread.Start(client);
            }
        }
        void setname(string name)
        {
            names.Add(name);
        }
        void Listen(object obj)
        {
            TcpClient TCPClient = (TcpClient)obj;
            while (true)
            {
                try
                {
                    byte[] fBuffer = new byte[1];
                    TCPClient.GetStream().Read(fBuffer, 0, 1);
                    byte[] buffer = new byte[(int)fBuffer[0]];
                    TCPClient.GetStream().Read(buffer, 0, (int)fBuffer[0]);
                    string message = Encoding.Unicode.GetString(buffer).Trim();
                    if (message.StartsWith("\\join"))
                    {
                        message = message.Remove(0, 5);
                        int a = 0;
                        for (int i = 0; i < banlist.Count; i++)
                        {
                            if (message.StartsWith(banlist[i]))
                            {
                                a = 1;
                            }
                        }

                        if (a == 0)
                        {
                            //int namespaceer = 0;
                            //foreach (char chars in message)
                            //{
                            //    namespaceer += 1;
                            //    if (chars == '+')
                            //        break;
                            //}
                            //    message = message.Remove(0, namespaceer);

                        }
                        else
                        {
                            //Write_to_output("Person on banlist");
                           // TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
                            //toRemove.Close();
                        }
                    }
                    else
                    {
                        foreach (TcpClient client in clients)
                        {
                            if (client != TCPClient)
                            {
                                SendMessage(message, client);
                            }
                        }
                        if (!CommandMode)
                        {
                            Write_to_output(message.Trim());
                        }
                        else
                        {

                        }
                    }
                }
                catch (Exception e)
                {
                    Write_to_output(e.ToString());
                }
            }
        }
        static string getip()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }
        public void Write_to_output(string towrite)
        {
            //check outputs length
            int numLines = 0;
            string text = Output.Text;
            numLines = Text.Split('\n').Length;
            if (numLines == MAXSIZE)
            {
                Output.Text = towrite;
            }
            else
            {
                Output.Text = Output.Text + $"\n" + towrite;
            }
        }
        private  void Input_Leave(object sender, EventArgs e)
        {
            string message = Input.Text;
            if (isserver == false)
            {
                //send client code
                SendMessage(message,Client);
            }
            else
            {
                //send server code
                foreach (TcpClient client in clients)
                {
                    SendMessage(message, client);
                }
            }
        }
    }
    }

请帮帮我...

【问题讨论】:

  • 我怀疑您没有正确关闭或Dispose()ing 客户端,尤其是在发生错误时
  • 这是否仅在您第二次单击启动服务器时发生?如果它确实是第一次发生,你能确认你只有一个程序实例在运行吗?
  • StackExchange 上有一个叫做 Code Review 的网站。
  • @LexLi 这个问题完全和完全无关紧要。 ... Code Review 不是一个旨在帮助您“修复”代码的站点。它可以改进工作代码(在不崩溃或花费千年的情况下做你想做的事)。更多信息请阅读A Guide to Code Review for Stack Overflow Users
  • 谢谢 Vogel612。我现在正在检查实例问题。

标签: c# .net sockets


【解决方案1】:

检查端口 TCP 2546 是否没有被侦听机器上的另一个进程或代码实例忙碌。 或者选择另一个空闲端口来监听。

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多