c #Socket类服务器和客户端都发送和接收

时间:2017-01-13 17:41:28

标签: c# visual-studio sockets tcp asyncsocket

我正在创建一个项目,我必须使用Socket类在c#中发送异步消息。

我已经创建了一个客户端连接到服务器和客户端向服务器发送消息的项目,但是现在我希望服务器使用相同的套接字将另一个byte []响应给客户端,但是我没有找到要做到这一点,我进行了一些测试,但它没有用。

例如,现在我有类似的东西(我把它简化为基础只是为了让你了解我的位置):

客户端:

namespace Client
{
    public partial class Client : Form
    {
        private Socket _clientSocket;
        private byte[] _buffer;

        public Client()
        {

            InitializeComponent();
        }

        public void btnConnect_Click(object sender, EventArgs e)
        {
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 3333), new AsyncCallback(ConnectCallback), null);
        }
        private void ConnectCallback(IAsyncResult AR)
        {

            _clientSocket.EndConnect(AR);

        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            string xmlstring = "test";
            byte[] xmlbuffer = Encoding.ASCII.GetBytes(xmlstring);
            _clientSocket.BeginSend(xmlbuffer, 0, xmlbuffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
        }
        private void SendCallback(IAsyncResult AR)
        {
            _clientSocket.EndSend(AR);
            _buffer = new byte[_clientSocket.ReceiveBufferSize];
        }
    }
}

服务器:

namespace Server
{
    public partial class Server : Form
    {
        private Socket _serversocket, _clientSocket;
        private byte[] _buffer;

        public Server()
        {
            InitializeComponent();
            StartServer();

        }

        private void StartServer()
        {
            _serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _serversocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
            _serversocket.Listen(0);
            _serversocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void AcceptCallback(IAsyncResult AR)
        {
            _clientSocket = _serversocket.EndAccept(AR);
            _buffer = new byte[_clientSocket.ReceiveBufferSize];
            _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
            _serversocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void ReceiveCallback(IAsyncResult AR)
        {
            int received = _clientSocket.EndReceive(AR);
            Array.Resize(ref _buffer, received);
            string text = Encoding.ASCII.GetString(_buffer);
            Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize);
        }
    }
}

我尝试以另一种方式发送答案,但它不起作用,所以我想问你该怎么做。

谢谢,如果帖子不对,我很抱歉,因为这是我的第一个。

0 个答案:

没有答案