Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 控制台应用程序上的套接字异常_C#_.net_Sockets_Tcp - Fatal编程技术网

C# 控制台应用程序上的套接字异常

C# 控制台应用程序上的套接字异常,c#,.net,sockets,tcp,C#,.net,Sockets,Tcp,我试图创建一个应用程序,在两个客户端(两个表单应用程序)之间创建一个绑定,以便通过TCP协议传输一些数据。我使用System.Net.Sockets(我是System.Net的初学者)在C#中编写了应用程序,但我遇到了以下错误: System.Net.Sockets.SocketException(0x80004005):连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能在System.Net.Sockets.Socket.DoConnection(EndP

我试图创建一个应用程序,在两个客户端(两个表单应用程序)之间创建一个绑定,以便通过TCP协议传输一些数据。我使用System.Net.Sockets(我是System.Net的初学者)在C#中编写了应用程序,但我遇到了以下错误:

System.Net.Sockets.SocketException(0x80004005):连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能在System.Net.Sockets.Socket.DoConnection(EndPoint endPointSnapshot,SocketAddress SocketAddress)响应192.168.2.101:100位于客户端的System.Net.Sockets.Socket.Connect(端点remoteEP)处的System.Net.Sockets.Socket.Connect(IPAddress地址,Int32端口)处的Form1.LoopConnect()

我必须说,这在我的机器上进行得很好,另一台机器通过路由器与我的机器绑定

这是服务器的代码:

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

namespace Server_003
{
    class Program
    {
        private static List<Socket> _clientSockets = new List<Socket>();
        private static List<string> _numeClient = new List<string>();
        private static List<int> _indexPartener = new List<int>();

        private static byte[] _buffer = new byte[10000];

        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        static void Main(string[] args)
        {
            SetUpServer();
            Console.ReadLine();
        }

        private static void SetUpServer()
        {
            //byte[] test = Encoding.ASCII.GetBytes("lose partener");
            //Console.WriteLine(test.Length);

            Console.WriteLine("Seting up server ... ");

            _serverSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.101"), 100));
            _serverSocket.Listen(5);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
        }

        private static string GetNume()
        {
            int index = 0;
            if (_numeClient.Count == 0)
                return "Client 0";
            else
                for (int i = 0; i < _numeClient.Count; i++)
                    if (_numeClient[i] != "Client " + index.ToString())
                        return "Client " + index.ToString();
                    else
                        index++;
            return "Client " + index.ToString(); 
        }

        private static void AcceptCallBack(IAsyncResult AR)
        {
            Socket socket = _serverSocket.EndAccept(AR);  //return client socket

            _clientSockets.Add(socket); 
            _indexPartener.Add(-1);  
            _numeClient.Add(GetNume()); 
            Console.WriteLine("Client conected with IP: " + socket.RemoteEndPoint);

            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);

            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null); //permitem sa mai accepte clienti
        }

        private static string GetNumeClienti()
        {
            string clienti = "";
            for (int i = 0; i < _numeClient.Count; i++)
                if(_indexPartener[i] == -1)
                    clienti += i.ToString() + " " + _numeClient[i] + "\r\n";
            return clienti;
        }

        private static string GetClientiPlusParteneri()
        {
            string clienti = "";
            for (int i = 0; i < _numeClient.Count; i++)
                if (_indexPartener[i] == -1)
                    clienti += _numeClient[i] + " Null\r\n";
                else
                    clienti += _numeClient[i] + " " + _numeClient[_indexPartener[i]] + "\r\n";
            return clienti;
        }

        private static void ReceiveCallBack(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;

            int index = _clientSockets.IndexOf(socket);

            int receive = socket.EndReceive(AR);
            byte[] DataBuffReceive = new byte[receive];

            if (receive == 13)
                _indexPartener[index] = -1;
            else
                if (_indexPartener[index] == -1)
                {
                    Array.Copy(_buffer, DataBuffReceive, receive);

                    string text = Encoding.ASCII.GetString(DataBuffReceive);
                    string raspuns = "Invalid request!";

                    if (text.ToLower() == "get time")
                    {
                        raspuns = DateTime.Now.ToLongTimeString();
                    }

                    if (text.IndexOf(' ') > 0 && text.Substring(0, text.IndexOf(' ')) == "NuMe")
                    {
                        _numeClient[index] = text.Substring(text.IndexOf(' ') + 1);
                        raspuns = "Nume setat la " + _numeClient[index];
                    }

                    if (text.ToLower() == "get clienti liberi")
                        raspuns = GetNumeClienti();

                    if (text.ToLower() == "get clienti si parteneri")
                        raspuns = GetClientiPlusParteneri();

                    if (text.ToLower() == "e--")
                    {
                        raspuns = "Deconectat!";

                        _clientSockets.RemoveAt(index);
                        _numeClient.RemoveAt(index);
                        _indexPartener.RemoveAt(index);

                        return;

                    }

                    byte[] DataBuffSend = Encoding.ASCII.GetBytes(raspuns);
                    socket.BeginSend(DataBuffSend, 0, DataBuffSend.Length, SocketFlags.None, new AsyncCallback(SendCallBack), socket); 
                }
                else
                    _clientSockets[index].BeginSend(DataBuffReceive, 0, DataBuffReceive.Length, SocketFlags.None, new AsyncCallback(SendCallBack), _clientSockets[index]);

            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
        }

        private static void SendCallBack(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            socket.EndSend(AR);
        }
    }
}

首先确保您可以与预期的目标IP进行通信。尝试
ping
控制台应用程序将运行的计算机的地址。如果您能与我们沟通,我们可以从那里继续。当您使用非标准端口号时,反恶意软件和防火墙总是会给您带来困难。您必须取消阻止端口100。端口100已取消阻止我已检查能否提供更多信息,一段客户端和服务器代码将非常有用…打开我的端口后,错误消失,但我的客户端没有响应
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Client_003
{
    public partial class Form1 : Form
    {

        private byte[] _buffer = new byte[10000];
        private Socket _clientSoket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private bool continuare = true;

        public Form1()
        {
            InitializeComponent();
            groupBox1.Text = "";
            groupBox1.Visible = false;
        }



        private void LoopConnect()
        {
            if (_clientSoket.Connected)
                MessageBox.Show("It's connected!");
            else
            {
                while (!_clientSoket.Connected)
                {
                    try
                    {
                        MessageBox.Show("Trying to connect!");

                        _clientSoket.Connect(IPAddress.Parse("192.168.2.101"), 100);                        

                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString());
                    }
                }
            }

            textBox2.Clear();
            textBox2.Text = "Connected!";
            groupBox1.Visible = true;
        }

        private void primire()
        {
            if (continuare)
            {
                int rec = _clientSoket.Receive(_buffer);
                byte[] data = new byte[rec];
                Array.Copy(_buffer, data, rec);
                string text = Encoding.ASCII.GetString(data);

                if (text.IndexOf(' ') > 0 && text.ToLower().Substring(0, text.IndexOf(' ')) == "acceptare_partener")
                {
                    DialogResult raspuns = MessageBox.Show("Acceptati ca partener pe " + text.Substring(text.IndexOf(' ') + 1), "Acceptare partener", MessageBoxButtons.YesNo);
                    if (raspuns == DialogResult.Yes)
                    {
                        byte[] cerere = Encoding.ASCII.GetBytes("yes");
                        _clientSoket.Send(cerere);

                        primire(); // expected confirmation
                    }
                    else
                    {
                        byte[] cerere = Encoding.ASCII.GetBytes("no");
                        _clientSoket.Send(cerere);

                        primire(); // expected confirmation
                    }
                }

                textBox2.Text += "\r\n" + text;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            LoopConnect();            
        }        

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] cerere = Encoding.ASCII.GetBytes(textBox1.Text);
            _clientSoket.Send(cerere);
            textBox1.Clear();

            primire();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_clientSoket.Connected)
            {
                continuare = false;
                byte[] cerere = Encoding.ASCII.GetBytes("e--");
                _clientSoket.Send(cerere);
                _clientSoket.Close();
            }
        }
    }
}