Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.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#客户端到服务器数据传输服务器正在接收以前的客户端消息Async Server-Async Client_C#_Sockets_Networking_Tcp_Asyncsocket - Fatal编程技术网

C#客户端到服务器数据传输服务器正在接收以前的客户端消息Async Server-Async Client

C#客户端到服务器数据传输服务器正在接收以前的客户端消息Async Server-Async Client,c#,sockets,networking,tcp,asyncsocket,C#,Sockets,Networking,Tcp,Asyncsocket,我正在尝试将消息从客户端发送到服务器,并使用c#中的套接字(tcp)显示它。有趣的是,服务器正确地接收到第一条消息并显示它,但在我将第二条消息从客户端发送到服务器后,服务器会显示客户端发送的前一条消息,即消息1 我修改了这个 还有这个 为了我的需要 为了更好地解释这个问题,我还录制了一段视频。由于某种原因,在我的节目中,服务器正在接收客户端发送的前一条消息,而不是新发送的消息 我试着尽量减少我的代码,这会造成尽可能多的问题。 谢谢 客户: using System; using Syste

我正在尝试将消息从客户端发送到服务器,并使用c#中的套接字(tcp)显示它。有趣的是,服务器正确地接收到第一条消息并显示它,但在我将第二条消息从客户端发送到服务器后,服务器会显示客户端发送的前一条消息,即消息1

我修改了这个

还有这个

为了我的需要

为了更好地解释这个问题,我还录制了一段视频。由于某种原因,在我的节目中,服务器正在接收客户端发送的前一条消息,而不是新发送的消息

我试着尽量减少我的代码,这会造成尽可能多的问题。 谢谢

客户:

using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.

namespace clientbugaramason
{
    public partial class Form1 : Form
    {
        static Socket client;


        public class StateObject
        {
            public Socket workSocket = null;
            public const int BufferSize = 256;
            public byte[] buffer = new byte[BufferSize];
            public StringBuilder sb = new StringBuilder();
        }
        private static ManualResetEvent connectDone =
           new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);

        public Form1()
        {
            InitializeComponent();
        }
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;

                client.EndConnect(ar);
                Console.WriteLine("Socket connected to {0}",
                    client.RemoteEndPoint.ToString());

                connectDone.Set();



            }
            catch (Exception e)
            {
                MessageBox.Show("Cant connect to server.Is it offline ? ");

                connectDone.Set();


            }
        }
        private void Send(String data)
        {
            MessageBox.Show("Data that i am sending to server " + data);
            // Convert the string data to byte data using ASCII encoding.  

            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.  
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.  
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.  
                int bytesSent = client.EndSend(ar);
                MessageBox.Show(bytesSent.ToString());

                // Signal that all bytes have been sent.  
                sendDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }


        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            // Click on the link below to continue learning how to build a desktop app using WinForms!
            System.Diagnostics.Process.Start("http://aka.ms/dotnet-get-started-desktop");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Send("message1<EOF>");

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

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

                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8080);

                // Create a TCP/IP socket.  
                client = new Socket(ipAddress.AddressFamily,
                   SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.  
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);


                connectDone.WaitOne();
                connectDone.Reset();






            }
            catch (Exception er)
            {
                MessageBox.Show("Cant connecttttt to server.Is it offline ? ");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Send("message2<EOF>");
        }
    }
}
使用系统;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
Net系统;
使用System.Net.Sockets;
使用系统线程;
//这是您的桌面应用程序的代码。
//按Ctrl+F5(或转到调试>不调试启动)运行应用程序。
命名空间clientbugaramason
{
公共部分类Form1:Form
{
静态套接字客户端;
公共类状态对象
{
公共套接字工作组=null;
public const int BufferSize=256;
公共字节[]缓冲区=新字节[BufferSize];
公共StringBuilder sb=新StringBuilder();
}
专用静态手动重置事件已完成=
新手动重置事件(错误);
私有静态手动重置事件sendDone=
新手动重置事件(错误);
私有静态手动重置事件接收完成=
新手动重置事件(错误);
公共表格1()
{
初始化组件();
}
私有无效连接回调(IAsyncResult ar)
{
尝试
{
套接字客户端=(套接字)ar.AsyncState;
客户端.EndConnect(ar);
WriteLine(“连接到{0}的套接字”,
client.RemoteEndPoint.ToString());
connectDone.Set();
}
捕获(例外e)
{
MessageBox.Show(“无法连接到服务器。它是否脱机?”);
connectDone.Set();
}
}
专用void发送(字符串数据)
{
Show(“我正在发送到服务器的数据”+数据);
//使用ASCII编码将字符串数据转换为字节数据。
byte[]byteData=Encoding.ASCII.GetBytes(数据);
//开始将数据发送到远程设备。
client.BeginSend(byteData,0,byteData.Length,0,
新的异步回调(SendCallback),客户端);
}
私有void SendCallback(IAsyncResult ar)
{
尝试
{
//从状态对象检索套接字。
套接字客户端=(套接字)ar.AsyncState;
//完成将数据发送到远程设备。
int bytesent=client.EndSend(ar);
Show(bytesent.ToString());
//表示已发送所有字节的信号。
sendDone.Set();
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
私有无效链接Label1\u链接已单击(对象发送方,链接LabelLinkClickedEventArgs e)
{
//单击下面的链接继续学习如何使用WinForms构建桌面应用程序!
系统.诊断.进程.启动(“http://aka.ms/dotnet-get-started-desktop");
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
发送(“消息1”);
}
私有void textBox1\u TextChanged(对象发送方,事件参数e)
{
}
私有无效按钮2\u单击(对象发送者,事件参数e)
{
尝试
{
IPAddress=IPAddress.Parse(“127.0.0.1”);
IPEndPoint remoteEP=新IPEndPoint(ipAddress,8080);
//创建TCP/IP套接字。
客户端=新套接字(ipAddress.AddressFamily,
流,ProtocolType.Tcp);
//连接到远程端点。
client.BeginConnect(remoteEP,
新的异步回调(ConnectCallback),客户端);
connectDone.WaitOne();
connectDone.Reset();
}
捕获(异常er)
{
显示(“无法将TTTT连接到服务器。它是否脱机?”);
}
}
私有无效按钮3\u单击(对象发送者,事件参数e)
{
发送(“消息2”);
}
}
}
服务器:

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.Net;
using System.Net.Sockets;
using System.Threading;

// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.

namespace serverbugaramason
{
    public partial class Form1 : Form
    {
        public class Player
        {
            // Client  socket.
            public Socket workSocket = null;
            public string userName = null;
            public bool questionAsked = false;
            public bool questionAnswered = false;
            public int score = 0;
            public string currentAnswer = null;
            // Size of receive buffer.
            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
            // Received data string.
            public StringBuilder sb = new StringBuilder();
            //Player-Info



            public void SetDefaults()
            {

            }

            public Player()
            {
            }

            public String pIPAddress;
        }


        public Form1()
        {
            InitializeComponent();
        }
        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public void StartListening()
        {

            Console.WriteLine("i am called");
            byte[] bytes = new Byte[1024];


            IPAddress ipAdress = IPAddress.Parse("127.0.0.1");
            IPEndPoint localEndPoint = new IPEndPoint(ipAdress, 8080);

            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Blocking = false;
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(50);


                Console.WriteLine("Server Started, waiting for connections...");
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);


            }
            catch (Exception e)
            {
                MessageBox.Show("Cant start server.");
                Console.WriteLine(e.ToString());
            }

            Console.Read();
        }
        public void AcceptCallback(IAsyncResult ar)
        {

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket clientsocket = listener.EndAccept(ar);
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

            // Signal the main thread to continue.
            allDone.Set();
            clientsocket.Blocking = false;      //set to non-blocking
                                                // Create the state object.
            Player PlayerInfo = new Player();
            PlayerInfo.workSocket = clientsocket;

            IPEndPoint thisIpEndPoint = PlayerInfo.workSocket.RemoteEndPoint as IPEndPoint; //Get Local Ip Address
            PlayerInfo.pIPAddress = thisIpEndPoint.Address.ToString();







            clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback),
                PlayerInfo);

        }
        public void ReadCallback(IAsyncResult ar)
        {

            Player PlayerInfo = (Player)ar.AsyncState;

            Socket clientsocket = PlayerInfo.workSocket;


            try
            {
                String content = String.Empty;


                int bytesRead = clientsocket.EndReceive(ar);

                if (bytesRead > 0)
                {

                    PlayerInfo.sb.Append(Encoding.ASCII.GetString(
                        PlayerInfo.buffer, 0, bytesRead));


                    content = PlayerInfo.sb.ToString();
                    int eofindex = content.IndexOf("<EOF>");
                    if (eofindex > -1)
                    {

                        content = content.Substring(0, eofindex);
                        if (content.Contains("message1"))
                        {
                            MessageBox.Show("Server speaking message1");
                            clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback),
                PlayerInfo);
                        }
                        if (content.Contains("message2"))
                        {
                            MessageBox.Show("server speaking message2");
                            clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback),
                PlayerInfo);
                        }



                    }
                    else
                    {
                        clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback),
                           PlayerInfo);
                    }
                }
                else
                {
                    clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback),
                              PlayerInfo);
                }
            }
            catch (Exception e)
            {

            }
        }



        private void button1_Click_1(object sender, EventArgs e)
        {
            StartListening();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
Net系统;
使用System.Net.Sockets;
使用系统线程;
//这是您的桌面应用程序的代码。
//按Ctrl+F5(或转到调试>不调试启动)运行应用程序。
命名空间服务器Bugaramason
{
公共部分类Form1:Form
{
公开课选手
{
//客户端套接字。
公共套接字工作组=null;
公共字符串userName=null;
public bool questionAsked=假;
已回答的公共布尔问题=错误;
公共智力得分=0;
公共字符串currentAnswer=null;
//接收缓冲区的大小。
public const int BufferSize=1024;
//接收缓冲区。
公共字节[]缓冲区=新字节[BufferSize];
//接收到的数据字符串。
公共StringBuilder sb=新StringBuilder();
//玩家信息
公共void SetDefaults()