客户端到服务器数据传输服务器正在接收以前的客户端消息Async Server - Async Client [英] Client to Server Data Tranfer Server is receiving previous client message Async Server - Async Client

查看:65
本文介绍了客户端到服务器数据传输服务器正在接收以前的客户端消息Async Server - Async Client的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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




我修改了这个
https ://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example



和此



https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

< br $>
满足我的需求。



我还录制了一个视频来更好地解释问题。发生的事情是我的程序的某些方面原因服务器正在接收客户发送的先前消息,而不是新发送的消息。





https://www.youtube.com/看?v = iPjZyzI5A5g& feature = youtu.be



我试过m尽量减少我的代码产生问题。

谢谢你b $ b $
客户:



  &NBSP;&NBSP;

使用System; 
使用System.Linq;
使用System.Text;
使用System.Windows.Forms;
使用System.Net;
使用System.Net.Sockets;
使用System.Threading;

//这是您桌面应用的代码。
//按Ctrl + F5(或转到Debug> Start Without Debugging)运行您的应用程序。

命名空间clientbugaramason
{
public partial class Form1:Form
{
static Socket client;


公共类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(例外e)
{
MessageBox.Show("无法连接到服务器。它离线了吗? ");

connectDone.Set();


}
}
private void发送(字符串数据)
{
MessageBox.Show("我要发送到的数据)服务器"+数据";
//使用ASCII编码将字符串数据转换为字节数据。

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

//开始将数据发送到远程设备。
client.BeginSend(byteData,0,byteData.Length,0,
new AsyncCallback(SendCallback),client);
}
private void SendCallback(IAsyncResult ar)
{
try
{
//从状态对象中检索套接字。
套接字客户端=(套接字)ar.AsyncState;

//完成将数据发送到远程设备。
int bytesSent = client.EndSend(ar);
MessageBox.Show(bytesSent.ToString());

//表示已发送所有字节的信号。
sendDone.Set();
}
catch(例外e)
{
Console.WriteLine(e.ToString());
}
}


private void linkLabel1_LinkClicked(object sender,LinkLabelLinkClickedEventArgs e)
{
//点击下面的链接继续学习如何使用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);

//创建TCP / IP套接字。
client = new Socket(ipAddress.AddressFamily,
SocketType.Stream,ProtocolType.Tcp);

//连接到远程端点。
client.BeginConnect(remoteEP,
新的AsyncCallback(ConnectCallback),客户端);


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






}
catch(例外)
{
MessageBox.Show ("Cant connecttttt到server.Is it offline?");
}
}

private void button3_Click(对象发件人,EventArgs e)
{
发送(" message2< EOF>");
}
}
}






服务器:



  &NBSP;&NBSP;

使用System; 
使用System.Collections.Generic;使用System.ComponentModel
;
使用System.Data;使用System.Drawing
;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;
使用System.Windows.Forms;

使用System.Net;
使用System.Net.Sockets;
使用System.Threading;

//这是您桌面应用的代码。
//按Ctrl + F5(或转到Debug> Start Without Debugging)运行您的应用程序。

命名空间serverbugaramason
{
公共部分类Form1:表格
{
公共类播放器
{
//客户端套接字。
public Socket workSocket = null;
public string userName = null;
public bool questionAsked = false;
public bool questionAnswered = false;
public int score = 0;
public string currentAnswer = null;
//接收缓冲区的大小。
public const int BufferSize = 1024;
//接收缓冲区。
public byte [] buffer = new byte [BufferSize];
//收到的数据字符串。
public StringBuilder sb = new StringBuilder();
//玩家信息



公共无效SetDefaults()
{

}

public Player()
{
}

public String pIPAddress;
}


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

public void StartListening()
{

Console.WriteLine("我被称为");
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("服务器启动,等待连接......");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);


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

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

//获取处理客户端请求的套接字。
套接字侦听器=(套接字)ar.AsyncState;
Socket clientsocket = listener.EndAccept(ar);
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

//发信号通知主线程继续。
allDone.Set();
clientsocket.Blocking = false; //设置为非阻塞
//创建状态对象。
Player PlayerInfo = new Player();
PlayerInfo.workSocket = clientsocket;

IPEndPoint thisIpEndPoint = PlayerInfo.workSocket.RemoteEndPoint as IPEndPoint; //获取本地IP地址
PlayerInfo.pIPAddress = thisIpEndPoint.Address.ToString();







clientsocket.BeginReceive(PlayerInfo.buffer,0,Player.BufferSize,0,新的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,新的AsyncCallback(ReadCallback),
PlayerInfo);
}
}
else
{
clientsocket.BeginReceive(PlayerInfo.buffer,0,Player.BufferSize,0,new AsyncCallback(ReadCallback),
PlayerInfo);
}
}
catch(例外e)
{

}
}



private void button1_Click_1(object sender,EventArgs e)
{
StartListening();
}
}
}




$

解决方案

您好LifeSuxTR,


感谢您发布此处。


您的问题,请尝试以下链接中的示例。


http ://csharp.net-informations.com/communications/csharp-socket-programming.htm


最好的问候,


Wendy


I am trying to send message from client to server and display it using sockets(tcp) in c#.The interesting thing is server receives first message correct and displays it,but after i send second message from client to server,server displays the previous message sent by client, message 1.


I modified this
https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example

and this

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

for my needs.

I also recorded a video to explain the problem better.What is happening is in some point of my programme for some reason server is receiving previous message sent by client,not the new sent message.


https://www.youtube.com/watch?v=iPjZyzI5A5g&feature=youtu.be

I tried to minimize my code which is creating problem as much as possible.
Thanks

Client:

    

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



Server:

    

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




解决方案

Hi LifeSuxTR,

Thank you for posting here.

For your question, please try the examples in the link below.

http://csharp.net-informations.com/communications/csharp-socket-programming.htm

Best Regards,

Wendy


这篇关于客户端到服务器数据传输服务器正在接收以前的客户端消息Async Server - Async Client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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