TCP / IP客户端和服务器基本使用和引用

时间:2017-04-01 12:45:02

标签: c# winforms tcp client-server nuget-package

我已将TCP/IPVS15 NuGet Packeges安装到我的项目中,而在参考文件中它是SimpleTCP,我正在重建项目,但对SimpleTcpClient client;它说:

  

抑制状态错误CS0246类型或命名空间名称   找不到'SimpleTcpServer'(您是否错过了使用   指令或程序集引用?)

不确定是什么原因造成的,也许我错过了一些参考资料甚至使用过。

客户端:

using System;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SimpleTcpClient client;

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            client.WriteLineAndGetReplay(txtMessage.Text, TimeSpan.FromSeconds(5));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new SimpleTcpClient();
            client.StringEncoder = Encoding.UTF8;
            client.DataRecevived += Client_DataReceived;
        }

        private void Client_DataReceived(object sender, SimpleTCP.Message e)
        {
            textBox1.Invoke((MethodInvoker)delegate ()
            {
                textBox1.Text += e.MessageString;
            });
        }
    }
}

服务器:

using System;
using System.Text;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SimpleTcpServer server;

        private void Form1_Load(object sender, EventArgs e)
        {
            server = new SimpleTcpServer();
            server.Delimeter = 0x13;
            server.StringEncoder = Encoding.UTF8;
            server.DataReceived += Server_DataReceived;
        }

        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            txtStatus.Invoke((MethodInvoker)delegate ()
            {
                txtStatus.Text += e.MessageString;
                e.ReplyLine(string.Format("You said: {0}", e.MessageString));
            });          
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            txtStatus.Text += "Server starting...";
            System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(txtHost.Text));
            server.Start(ip, Convert.ToInt32(txtPort.Text));
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (server.IsStarted)
            {
                server.Stop();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

要回答您的问题,您会收到此错误,因为您的代码中未包含using SimpleTCP;

每个表单的开头应如下所示:

using SimpleTCP;
using System;
using System.Net;
using System.Windows.Forms;

话虽如此,代码仍会有一些问题。

  1. 您的客户表单中没有client.Connect(IP, PORT);。要创建server < > client连接,必须有一个侦听服务器和一个连接到它的客户端。在您的情况下,只有一个监听服务器。

  2. server表单中,您应该拨打IPAddress.Parse()。用法示例:IPAddress.Parse("127.0.0.1");

  3. 您不需要Invoke任何Form成员,因为您没有使用任何类型的多线程,除非SimpleTCP默认情况下这样做,这是非常不可能。

  4. 此外,整个项目似乎一团糟。如果您还在开始使用,我强烈建议您使用Console Application,因为它们更宽容且使用起来非常简单。

    我还建议您详细了解C# events及其工作原理。

    以下是使用server < > client的{​​{1}}项目,您的配置和SimpleTCP可以帮助您入门。

    服务器:

    Console Application

    客户端:

    using System;
    using System.Net;
    using SimpleTCP;
    using System.Text;
    
    namespace server
    {
        class Program
        {
            static void Main(string[] args)
            {
                SimpleTcpServer server = new SimpleTcpServer(); //Instantiate server.
                server.Delimiter = 0x13; //Config
                server.StringEncoder = Encoding.UTF8; //Config
                server.DataReceived += Server_DataReceived; //Subscribe to DataRecieved event.
                IPAddress ip = IPAddress.Parse("127.0.0.1"); //IP Address using .Parse()
                int port = 6500; //Port number
                server.Start(ip, port); //Start listening to incoming connections and data.
                Console.ReadKey(); //Pause the console.
            }
    
            static void Server_DataReceived(object sender, SimpleTCP.Message m)
            {
                Console.WriteLine(m.MessageString); //Write message to console.
                string replyMessage = String.Format("You said {0}", m.MessageString); //This is the reply message
                m.ReplyLine(replyMessage); //Send reply message back to client.
            }
        }
    }
    

    我希望这对你的旅程有所帮助,祝你好运!

答案 1 :(得分:0)

它有点旧,但是我想这可能很有趣。 我之所以来到这里,是因为我观看了YouTube视频(https://www.youtube.com/watch?v=ve2LX1tOwIM),上面的代码完全一样。 视频中的问题是我被切断了,看不到部分代码。在视频的客户端代码中,如问题中的上面的代码一样,某些行没有完整显示。似乎缺少该行client.Connect(TxtHost.Text,Convert.ToInt32(TxtPort.Text)); 即使在服务器事件btnStart_Click中,该视频也存在错误,其中首先显示代码System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(txtHost.Text));就像上面的服务器代码一样。即使在此情况下,我也无法调试,在接近尾声的地方观看视频,这可能是在System.Net.IPAddress ip = System.Net.IPAddress中更改了代码(但并没有在所有视频中显示)。解析(TxtHost.Text);

对于那些确切地来自该视频的人,我发布了完整的代码,这些更正以及其他一些更改:

客户端:

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

    namespace TelnetClient
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }


            SimpleTcpClient client;

            private void BtnConnect_Click(object sender, EventArgs e)
            {
                try
                {
                    //System.Net.IPAddress ip = System.Net.IPAddress.Parse(TxtHost.Text);
                    client.Connect(TxtHost.Text, Convert.ToInt32(TxtPort.Text));

                    BtnConnect.Enabled = false;
                    BtnClose.Enabled = true;
                    BtnSend.Enabled = true;
                    TxtHost.Enabled = false;
                    TxtPort.Enabled = false;
                    TxtMessages.Enabled = true;
                }
                catch (Exception)
                {
                    TxtStatus.Text = "Error during connection... please check host and port...";
                    TxtStatus.AppendText(Environment.NewLine);
                }

            }

            private void Form1_Load(object sender, EventArgs e)
            {
                client = new SimpleTcpClient();
                client.StringEncoder = Encoding.UTF8;
                client.DataReceived += Client_DataReceived;
            }

            private void Client_DataReceived(object sender, SimpleTCP.Message e)
            {
                TxtStatus.Invoke((MethodInvoker)delegate ()
                {
                    TxtStatus.Text += e.MessageString;
                    TxtStatus.AppendText(Environment.NewLine);
                });
            }

            private void BtnSend_Click(object sender, EventArgs e)
            {
                //client.WriteLineAndGetReply(TxtMessages.Text, TimeSpan.FromSeconds(3));
                client.WriteLineAndGetReply(TxtMessages.Text, TimeSpan.FromSeconds(0));

                TxtMessages.Text = "";
            }

            private void BtnClose_Click(object sender, EventArgs e)
            {
                try
                {

                    client.Disconnect();

                    BtnConnect.Enabled = true;
                    BtnClose.Enabled = false;
                    BtnSend.Enabled = false;
                    TxtHost.Enabled = true;
                    TxtPort.Enabled = true;
                    TxtMessages.Enabled = false;
                    TxtMessages.Text = "";
                }
                catch (Exception)
                {

                    TxtStatus.Text = "Error during closing connection...";
                    TxtStatus.AppendText(Environment.NewLine);
                }


            }
        }
    }

服务器:

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

namespace TelnetServer
{

    public partial class TelnetServer : Form
    {
        public TelnetServer()
        {
            InitializeComponent();
        }
        SimpleTcpServer server;

        private void TelnetServer_Load(object sender, EventArgs e)
        {
            server = new SimpleTcpServer();
            server.Delimiter = 0x13;//enter
            server.StringEncoder = Encoding.UTF8;
            server.DataReceived += Server_DataReceived;

        }

        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            TxtStatus.Invoke((MethodInvoker)delegate ()
            {
                TxtStatus.Text += e.MessageString;
                TxtStatus.AppendText(Environment.NewLine);
                //e.ReplyLine(String.Format("You said: {0}", e.MessageString));
                server.Broadcast(e.MessageString);
            });
        }

        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                System.Net.IPAddress ip = System.Net.IPAddress.Parse(TxtHost.Text);
                //System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(TxtHost.Text));
                server.Start(ip, Convert.ToInt32(TxtPort.Text));

                TxtStatus.Text = "Server starting...";
                TxtStatus.AppendText(Environment.NewLine);

                BtnStart.Enabled = false;
                BtnStop.Enabled = true;
                TxtHost.Enabled = false;
                TxtPort.Enabled = false;

            }
            catch (Exception)
            {
                TxtStatus.Text = "Error during starting... please check host and port...";
                TxtStatus.AppendText(Environment.NewLine);
            }   

        }

        private void BtnStop_Click(object sender, EventArgs e)
        {
            BtnStart.Enabled = true;
            BtnStop.Enabled = false;
            TxtHost.Enabled = true;
            TxtPort.Enabled = true;

            if (server.IsStarted)
                server.Stop();

            TxtStatus.Text = "Server stopped... ";
            TxtStatus.AppendText(Environment.NewLine);
        }
    }
}