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

时间:2014-02-06 21:22:42

标签: c# .net sockets tcp

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

  

System.Net.Sockets.SocketException(0x80004005):连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能在系统响应192.168.2.101:100 Client.003.Form1上System.Net.Sockets.Socket.Connect(IPAddress地址,Int32端口)的System.Net.Sockets.Socket.Connect(EndPoint remoteEP)上的.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,SocketAddress socketAddress) .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);
        }
    }
}

这是客户端代码(表单应用程序):

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();
            }
        }
    }
}

0 个答案:

没有答案