需要帮助在localhost上设置客户端服务器 [英] Need help setting up client server on localhost

查看:90
本文介绍了需要帮助在localhost上设置客户端服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,已经花了很多年的VB,我正在尝试设置一个简单的客户端/服务器通信。初始套接字连接似乎工作正常但是,在设置第一个连接后,客户端断开连接,因此不再进行通信。



服务器代码

I am new to C# having spent many years with VB and I'm trying to setup a simple client/Server communication. Th initial socket connection appears to work perfectly however, after the first connection has been setup, the client drops the connection so no more communication can occur.

Server Code

<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Server
{
    class Server
    {
        static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
            s.Bind(ipLocal);
            s.Listen(4);

            Console.WriteLine("Waiting for client ...\n");
            
            Socket newConnection = s.Accept();
            if (newConnection != null)
            {            
                while (true)
                {
                    byte[] buffer = new byte[4096];

                    try
                    {
                        int result = newConnection.Receive(buffer);

                        if (result > 0)
                        {
                            ASCIIEncoding encoder = new ASCIIEncoding();
                            String recdMsg = encoder.GetString(buffer, 0, result);

                            byte[] array = Encoding.ASCII.GetBytes("" + recdMsg);

                            Dungeon dungeon = new Dungeon();
                            Console.WriteLine("Welcome:  " + recdMsg);
                            int bytesSent = s.Send(buffer);
                            dungeon.Init();
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine(ex);    	
                    }                    
                }
            }
        }
        private string v1 = "Room 0";
        private int v2 = 0;
        internal static Room Dungeon(string v1, int v2)
        {
            throw new NotImplementedException();
        }
    }
}





客户代码



Client Code

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

namespace Client
{
    class client
    {
        static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
			bool connected = false;

			while (connected == false) 
			{
				try 
				{
					s.Connect (ipLocal);
					connected = true;
                    Console.Write("We are connected!\n" , 0);

                }
                catch (Exception) 
				{

                    Console.Write("Failed", 0);
                    Thread.Sleep (1000);
				}
			}

            int ID = 0;

            while (true)
            {
                String Msg = Console.ReadLine();
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(Msg);
                
                String DunMessage = encoder.GetString(buffer, 0, ID);
                Console.WriteLine(DunMessage);

                try
                {
                    Console.WriteLine("Writing to server: " + Msg);
                    int bytesSent = s.Send(buffer);
                    s.Receive(buffer);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex);	
                }
                

                Thread.Sleep(1000);
            }
        }
    }
}



任何人都可以指出我哪里出错了?

谢谢



我的尝试:



我找不到任何其他东西来尝试建立连接。这显然是非常基本的东西。


Can anyone please point out where I'm going wrong?
Thanks

What I have tried:

I can't find anything else to try having established a connection. It's obviously something really basic.

推荐答案

我看到至少一个问题:

你的客户端根据输入的长度创建一个缓冲区字符串并发送。您的服务器使用大小为4096的本地缓冲区来接收和发送内容。但它使用 Send(byte [])重载,它发送整个数组(4096)字节。您的客户端调用 Receive(byte []),它在缓冲区已满后停止。但是这个缓冲区很可能比4096小得多。结果你会在发送下一个命令后收到垃圾(4096字节的剩余数据)。



这个问题的解决方案是让服务器只发送使用发送(byte []缓冲区,Int32,SocketFlags)过载传递<$ c的字节数$ c>结果表示要发送的字节数。



最终的解决方案(不只是回显)也应该使用pre用于在客户端接收的大小数组,以避免在答案长于请求时溢出。



但以上仅适用于使用 localhost 。使用远程连接时,如果数据大于传输包大小,它可能不再起作用,因为额外的数据包可能需要更长的时间才能传输,因此您只能在任一侧接收部分数据。这就是为什么互联网通信使用包含指定总长度的字段的协议,以便接收方知道总共需要接收多少字节。
I see at least one problem:
Your client creates a buffer according to the length of the entered string and sends that. Your server uses a local buffer of size 4096 to receive and sends the content back. But it uses the Send(byte[]) overload which sends the whole array (4096) bytes. Your client calls Receive(byte[]) which stops after the buffer is full. But that buffer is very probable much smaller than 4096. As a result you would receive garbage (the remaing data from the 4096 bytes) after sending the next command.

The solution for this problem is letting the server only send the number of bytes which has been received by using the Send(byte[] buffer, Int32, SocketFlags) overload passing result for the number of bytes to be send.

The final solution (not just echoing back) should also use a pre sized array for receiving in the client to avoid overflows when the answer is longer than the request.

But the above applies only when using localhost. With remote connections it might not work anymore when the data is larger than the transport package size because additional packets might take more time to be transferred so that you only receive partial data on either side. That is why internet communicatios use "protocols" containing a field that specifies the total length so that the receiver knows how many bytes has to be received in total.


这篇关于需要帮助在localhost上设置客户端服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆