C#套接字连接问题

时间:2013-01-14 22:34:30

标签: c# sockets connection disconnect

好的,所以我的代码中有一个套接字连接导致了问题。它连接然后很快断开连接。它在“connections ++”之后断开连接线。有什么想法吗?

根据以下表格要求提供所有代码

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;

namespace Middleware
{
public partial class Middleware : Form
{

    //variables
    private Socket server;
    private Socket remoteclient;
    private Socket clientreturn;
    private Socket serversync;
    private byte[] data = new byte[1024];
    private byte[] datars = new byte[1024];
    private int connections = 0;

    public Middleware()
    {
        InitializeComponent();
        Control.CheckForIllegalCrossThreadCalls = false;
    }

    private void Middleware_Load(object sender, EventArgs e)
    {

    }

    void OnConnectedRemote(IAsyncResult result)
    {
        try
        {
            remoteclient.EndConnect(result);
        }
        catch
        {
            remoteclient.Close();
        }
    }

    void OnConnected(IAsyncResult result)
    {
        Socket client = server.EndAccept(result);

        connections++;
        server.BeginAccept(new AsyncCallback(OnConnected), null);
        try
        {
            txtStatus.Text = "" + connections;
            byte[] message = Encoding.ASCII.GetBytes("Welcome to my server");
            client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnDataSent), client);
        }
        catch
        {
            client.Close();
        }
    }

    void OnConnectedSync(IAsyncResult result)
    {
        Socket sync = serversync.EndAccept(result);

        connections++;
        //serversync.BeginAccept(new AsyncCallback(OnConnectedSync), null);
        try
        {
            txtStatus.Text = "" + connections;
            byte[] message = Encoding.ASCII.GetBytes("Connected to Middleware");
            sync.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnDataSentSync), sync);
        }
        catch
        {
            sync.Close();
        }
    }

    void OnDataSent(IAsyncResult result)
    {

        Socket client = (Socket)result.AsyncState;

        try
        {

            //end send and begin receive from client
            int sent = client.EndSend(result);
            client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);

        }
        catch (SocketException)
        {

            //close client
            client.Close();

        }
    }


    void OnDataSentSync(IAsyncResult result)
    {

        Socket sync = (Socket)result.AsyncState;

        try
        {

            //end send and begin receive from client
            int sent = sync.EndSend(result);

            sync.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceivedSync), sync);

        }
        catch (SocketException)
        {

            //close client
            sync.Close();

        }
    }

    void OnDataReceivedSync(IAsyncResult result)
    {

        Socket sync = (Socket)result.AsyncState;
        //clientreturn = (Socket)result.AsyncState;



    }

    void OnDataSentWaiting(IAsyncResult result)
    {

        Socket sync = (Socket)result.AsyncState;

        try
        {

            //end send and begin receive from client
            int sent = sync.EndSend(result);
            //sync.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), sync);

        }
        catch (SocketException)
        {

            //close client
            sync.Close();

        }
    }

    void OnDataReceived(IAsyncResult result)
    {

        Socket client = (Socket)result.AsyncState;
        clientreturn = (Socket)result.AsyncState;

        try
        {

            //if nothing is received then close connection
            //otherwise get message and add to list box
            //create newsocket, bind and listen to create server connection
            //begin accept
            int receive;
            receive = client.EndReceive(result);
            //string port = (((IPEndPoint)client.RemoteEndPoint).Port.ToString ());


            if (receive == 0)
            {
                client.Close();
                return;
            }
            else
            {

                string message = Encoding.ASCII.GetString(data, 0, receive);
                lstAll.Items.Add(message);
                txtSent.Text = message;
                byte[] echomessage = Encoding.ASCII.GetBytes(message);

                bool check = remoteclient.Poll(1000, SelectMode.SelectRead);
                bool avail = (remoteclient.Available == 0);
                if (check & avail)
                {

                    btnConnect.Enabled = true;
                    btnDisconnect.Enabled = false;
                    MessageWait(message);
                    //serversync.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnDataSentWaiting), serversync);
                    //client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);

                }
                else
                {

                    client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);
                    remoteclient.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnRemoteDataSent), remoteclient);

                }
            }
        }
        catch (SocketException)
        {
            //close client
            client.Close();
        }


    }

    private void MessageWait(string message)
    {
        byte[] echomessage = Encoding.ASCII.GetBytes(message);
        serversync.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnDataSentSync), null);
    }

    void OnRemoteDataSent(IAsyncResult result)
    {
        try
        {

            int sent = remoteclient.EndSend(result);
            remoteclient.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnRemoteDataReceived), null);

        }
        catch (SocketException)
        {

            //close server connection
            remoteclient.Close();

        }

    }

    void OnRemoteDataReceived(IAsyncResult result)
    {
        try
        {

            int receive = remoteclient.EndReceive(result);
            string message = Encoding.ASCII.GetString(data, 0, receive);
            txtReceived.Text = message + " from Middle";
            datars = Encoding.ASCII.GetBytes(txtReceived.Text);
            clientreturn.BeginSend(datars, 0, datars.Length, SocketFlags.None, new AsyncCallback(OnDataSentBack), clientreturn);

        }
        catch (SocketException)
        {

            //close server
            clientreturn.Close();

        }
    }

    void OnDataSentBack(IAsyncResult result)
    {

        Socket client = (Socket)result.AsyncState;

        try
        {

            int sent = client.EndSend(result);

        }
        catch (SocketException)
        {
            //closeserver
            client.Close();
        }

    }

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

            btnConnect.Enabled = false;
            remoteclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), 2000);
            remoteclient.BeginConnect(remoteEndPoint, new AsyncCallback(OnConnectedRemote), null);
        }
        catch
        {
            remoteclient.Close();
        }
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        int port;
        port = int.Parse(txtPort.Text);
        btnStart.Enabled = false;

        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEP = new IPEndPoint(0, port);
        server.Bind(localEP);
        server.Listen(4);
        server.BeginAccept(new AsyncCallback(OnConnected), null);

        txtStatus.Text = "Waiting for client...";
    }

    private void btnSyncC_Click(object sender, EventArgs e)
    {
        int port;
        port = int.Parse(txtPort.Text);
        btnStart.Enabled = false;

        serversync = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEP2 = new IPEndPoint(0, port);
        serversync.Bind(localEP2);
        serversync.Listen(1);
        serversync.BeginAccept(new AsyncCallback(OnConnectedSync), null);

        txtStatus.Text = "Waiting for sync client...";
    }

}

}

1 个答案:

答案 0 :(得分:0)

我敢打赌,txtStatus对象有问题,你实际上得到了一个N​​ullReferenceException,它被捕获,被忽略,并导致套接字立即关闭。