使用套接字将数据发送到服务器并存储在SQL Server中

时间:2016-04-17 13:40:46

标签: c# sql-server sockets asynchronous

我正在尝试使用套接字编程从客户端接收一些信息(例如:磁盘使用或类似的东西)。

我正在为多个客户端使用异步方法,并尝试写入SQL Server,但我没有将整个信息存储到SQL Server。客户端和服务器之间的字节数组上的通信流,但如何在通信期间将此字节数组存储到SQL Server?

1 个答案:

答案 0 :(得分:0)

对于迟到的回复人员抱歉,

这是代码。有2个项目。其中一个是服务器,另一个是客户端。服务器项目中有两个类。

类;

class Listener
{
    private Socket _socket;

    public bool Listening { get; private set; }
    public int Port { get; private set; }

    public Listener(int port)
    {
        Port = port;
        _socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
    }

    public void Start()
    {
        if (Listening)
        {
            return;
        }

        _socket.Bind(new IPEndPoint(0,Port));
        _socket.Listen(0);
        _socket.BeginAccept(callback, null);
        Listening = true;
    }

    public void Stop()
    {
        if (!Listening)
        {
            return;
        }

        _socket.Close();
        _socket.Dispose();
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }

    void callback(IAsyncResult ar)
    {
        try
        {
            Socket socket = this._socket.EndAccept(ar);

            if (SocketAccepted!=null)
            {
                SocketAccepted(socket);
            }
            this._socket.BeginAccept(callback, null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public delegate void SocketAcceptedHandler(Socket e);

    public event SocketAcceptedHandler SocketAccepted;
}


class Client
{
    public string ID { get; private set; }
    public IPEndPoint EndPoint { get; private set; }

    private Socket sck;

    public Client(Socket accepted)
    {
        sck = accepted;
        ID = Guid.NewGuid().ToString();
        EndPoint = (IPEndPoint)sck.RemoteEndPoint;
        sck.BeginReceive(new byte[] {0}, 0, 0, 0, callback, null);
    }

    void callback(IAsyncResult ar)
    {
        try
        {
            sck.EndReceive(ar);

            byte[] buf=new byte[8192];
            int rec = sck.Receive(buf, buf.Length, 0);

            if (rec<buf.Length)
            {
                Array.Resize<byte>(ref buf, rec);
            }
            if (Received!=null)
            {
                Received(this, buf);
            }

            sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);

        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
            sck.Close();

            if (Disconnected!=null)
            {
                Disconnected(this);
            }
        }

    }

    public void Close()
    {
        sck.Close();
        sck.Dispose();
    }
    public delegate void ClientReceivedHandler(Client sender, byte[] data);
    public delegate void ClientDiscconnectedHandler(Client sender);

    public event ClientReceivedHandler Received;
    public event ClientDiscconnectedHandler Disconnected;
}

服务器项目主窗体:

Server Application

public partial class Main : Form
{
    private static Listener _listener;

    public Main()
    {
        InitializeComponent();
        _listener = new Listener(8);
        _listener.SocketAccepted += new Listener.SocketAcceptedHandler(_listenerSocketAccepted);
        _listener.Start();

    }

    private void _listenerSocketAccepted(Socket e)
    {
        Client client = new Client(e);
        client.Received += new Client.ClientReceivedHandler(client_Received);
        client.Disconnected += new Client.ClientDiscconnectedHandler(client_Disconnected);


        Invoke((MethodInvoker)delegate
        {
            ListViewItem i=new ListViewItem();
            i.Text = client.EndPoint.ToString();
            i.SubItems.Add(client.ID);
            i.SubItems.Add("XXX");
            i.SubItems.Add("XXX");
            i.Tag = client;
            listViewClients.Items.Add(i);

            //textBox1.Text = "New Connection : " + e.RemoteEndPoint + "    Time : " + DateTime.Now;
        });
    }

    private void client_Disconnected(Client sender)
    {
        Invoke((MethodInvoker)delegate
        {
            for (int i = 0; i < listViewClients.Items.Count; i++)
            {
                Client client=listViewClients.Items[i].Tag as Client;

                if (client.ID==sender.ID)
                {
                    listViewClients.Items.RemoveAt(i);
                    break;
                }
            }
        });
    }

    private void client_Received(Client sender, byte[] data)
    {
        Invoke((MethodInvoker)delegate
        {
            for (int i = 0; i < listViewClients.Items.Count; i++)
            {
                Client client = listViewClients.Items[i].Tag as Client;

                if (client.ID == sender.ID)
                {
                    listViewClients.Items[i].SubItems[2].Text = Encoding.Default.GetString(data);
                    listViewClients.Items[i].SubItems[3].Text = DateTime.Now.ToString();
                    break;
                }
            }
        });
    }

    private void Main_Load(object sender, EventArgs e)
    {

    }
}

客户端主表单:

Client Application

public partial class Main : Form
{
    Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    public Main()
    {
        InitializeComponent();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        sck.Connect("127.0.0.1", 8);
        MessageBox.Show("Connected");
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        int s = sck.Send(Encoding.Default.GetBytes(txtMsg.Text));

        if (s>0)
        {
            MessageBox.Show("Message Sent..");
        }
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        sck.Close();
        sck.Dispose();
        Close();
    }

    private void Main_Load(object sender, EventArgs e)
    {
        //lis
    }
}

我有2个问题。

1-如何从客户端向sql插入数据?

2-当我用btnClose关闭我的客户端应用程序时,listview项目闪烁并且不会消失。