Windows窗体中的套接字编程 [英] Socket Programming in windows form

查看:77
本文介绍了Windows窗体中的套接字编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看此服务器端代码,如果我想将数据从服务器发送到客户端我该如何发送它请在此代码中帮助我,我的Send_Received函数给出找不到对象引用..





Please review this server side code if i want to send data from server to client how can i send it please help me in this code my Send_Received function is giving object reference not found..


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

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

        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static List<socket> _clientSockets = new List<socket>();
        private static readonly int _BUFFER_SIZE = 2048;
        private static byte[] _buffer = new byte[_BUFFER_SIZE];
        string text;
        Socket current;
        Socket test;
        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.richTextBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.richTextBox1.Text += text + "\n";
            }
        }
        private void SetupServer()
        {
            SetText("Setting up server...");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 14000));
            _serverSocket.Listen(5);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            SetText("Server Setup");
        }

        /// <summary>
        /// Close all connected client (we do not need to shutdown the server socket as its connections
        /// are already closed with the clients)
        /// </summary>
        private static void CloseAllSockets()
        {
            foreach (Socket socket in _clientSockets)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }

            _serverSocket.Close();
        }

        private void AcceptCallback(IAsyncResult AR)
        {
            Socket socket = null;

            try
            {
                socket = _serverSocket.EndAccept(AR);
            }
            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
            {
                return;
            }

            _clientSockets.Add(socket);
            socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            SetText("Client connected, waiting for request...");
            test = (Socket)AR.AsyncState;
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
        private void ReceiveCallback(IAsyncResult AR)
        {
            current = (Socket)AR.AsyncState;
            int received = 0;

            try
            {
                received = current.EndReceive(AR);
            }
            catch (SocketException)
            {
                SetText("Client forcefully disconnected");
                current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
                _clientSockets.Remove(current);
                return;
            }

            byte[] recBuf = new byte[received];
            Array.Copy(_buffer, recBuf, received);
            text = Encoding.ASCII.GetString(recBuf);
            SetText("Received Text: " + text);
            if (text.ToLower() == "get tim") // Client requested time
            {
                SetText("Text is a get time request");
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                current.Send(data);
                SetText("Time sent to client");
            }
            else if (text.ToString() == "C1") // Client wants to exit gracefully
            {
                SetText("Received :: C1");
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                current.Send(data);
            }

            else
            {
                SetText("Server is sending invalid packet");
                SetText("Warning Sent");
            }
            current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveCallback), current);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetupServer();
        }
        private void Send_Received(string mess)
        {
            byte[] data = Encoding.ASCII.GetBytes(mess);
            test.Send(data);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            CloseAllSockets();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Send_Received(textBox1.Text);
        }
 
    }
}





代码块添加 - OriginalGriff [/ edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

由于你只从你的按钮点击事件中调用 Send_Received mess 参数来自TextBox.Text,因此不能为null,并且 test 仅在<$ c中分配了一个值$ c> AcceptCallback 方法,我首先在 AcceptCallback 的开头加一个断点,然后单步调试代码,看看是否 test 实际上被赋予了有效值。如果没有,为什么不呢。



但这不是我们可以做的事情 - 我们无法访问您的系统进行测试,所以您必须这样做自己调查。
Since you call Send_Received only from your button click event, the mess parameters comes from a TextBox.Text and thus can't be null, and test is only assigned a value in your AcceptCallback method, I would start by putting a breakpoint at the start of AcceptCallback and stepping through the code to see if test is ever actually given a valid value. And if not, why not.

But that's not something we can do - we don't have access to your system to test it, so you will have to do the investigation yourself.


这篇关于Windows窗体中的套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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