Friday, 31 January 2014

c# async TCP/IP server & multiple clients

    2 computers cross-over cable connection 

start client 1

get server @ from server screen

client 1 connect to server

client 1 send to server

client 1 get reply from server

while client 1 still alive, client 2 talk to server

client 2 gets no reply

while client 1,2 online, client 3 connects to server


client 4 joins with other clients

client 4 doesn't get reply immediately

client 1 disconnected

server reply to client 2

client 2 finishes

client 3 receive from server and leaves

client 4 gets message

client 4 quit

server show local addresses

server receive call from 4 client, handle them 1 by 1.

client 1 gone, server has time with 2nd client

client 2 gone, server tackle with client 3

most clients are gone, deal with the last one

everybody left, waiting for new client

computers connect via router by cable or wifi 


start client

ping server

no data lose

start server

server call back

communication successful, next client


//tcpserver async
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 server_async
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            richTextBox1.AppendText("local server address\n");

            foreach (IPAddress x in ipHostInfo.AddressList)
            {
                richTextBox1.AppendText(x.ToString()+"\n");
            }

            server = new Socket(AddressFamily.InterNetwork,
                   SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            server.Bind(iep);
            server.Listen(5);
            server.BeginAccept(new AsyncCallback(AcceptConn), server);
        }

        public delegate void callrichtext(String ss);
        public callrichtext myDelegate;

        public void richtextappend(String s)
        {
            richTextBox1.AppendText(s);
        }

        public delegate void callrichtext1(String ss);
        public callrichtext1 myDelegate1;

        public void richtextappend1(String s)
        {
            richTextBox2.AppendText(s);
        }

        private Socket server, oldclient;
        private byte[] data = new byte[1024];
        private int size = 1024;

        private void AcceptConn(IAsyncResult iar)
        {
            Socket oldserver = (Socket)iar.AsyncState;
            oldclient = oldserver.EndAccept(iar);
            richTextBox1.Invoke(this.myDelegate, new Object[] { "Connected to: " + oldclient.RemoteEndPoint.ToString() + "\n" });
            string stringData = "Welcome to my server";
            byte[] message1 = Encoding.ASCII.GetBytes(stringData);
            oldclient.BeginSend(message1, 0, message1.Length, SocketFlags.None,
                        new AsyncCallback(SendData), oldclient);
        }

        private void SendData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            client.BeginReceive(data, 0, size, SocketFlags.None,
                        new AsyncCallback(ReceiveData), client);
        }

        private void ReceiveData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int recv = client.EndReceive(iar);
            //MessageBox.Show(recv.ToString());
         
            if (recv == 0)
            {
                client.Close();
                richTextBox1.Invoke(this.myDelegate, new Object[]{ "Waiting for client..."+"\n"});
                server.BeginAccept(new AsyncCallback(AcceptConn), server);
                return;
            }
            string receivedData = Encoding.ASCII.GetString(data, 0, recv);
            richTextBox2.Invoke(this.myDelegate1, new Object[] {receivedData + "\n"});
            byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
            client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
                         new AsyncCallback(SendData), client);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.myDelegate = new callrichtext(richtextappend);
            this.myDelegate1 = new callrichtext1(richtextappend1);
        }

    }
}

----------------------------------------------------------------------------
//tcpclient async
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 tcpclient_async
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress x in ipHostInfo.AddressList)
            {
                comboBox1.Items.Add (x.ToString());
            }
        }

        public delegate void callrichtext(String ss);
        public callrichtext myDelegate;

        public void richtextappend(String s)
        {
            richTextBox1.AppendText(s);
        }

        public delegate void callrichtext1(String ss);
        public callrichtext1 myDelegate1;

        public void richtextappend1(String s)
        {
            richTextBox2.AppendText(s);
        }

        public delegate void callrichtext2(String ss);
        public callrichtext2 myDelegate2;

        public void richtextappend2(String s)
        {
            richTextBox3.AppendText(s);
        }

        public delegate void buttonenable();
        public buttonenable myDelegate3;

        public void button()
        {
            button2.Enabled=true;
        }

        private Socket client;
        private byte[] data = new byte[1024];
        private int size = 1024;

        private void Form1_Load(object sender, EventArgs e)
        {
            this.myDelegate = new callrichtext(richtextappend);
            this.myDelegate1 = new callrichtext1(richtextappend1);
            this.myDelegate2 = new callrichtext2(richtextappend2);
            this.myDelegate3 = new buttonenable(button);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox3.AppendText( "Connecting... \n");
            Socket newsock = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox1.Text), 9050);
            newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] message = Encoding.ASCII.GetBytes(richTextBox2.Text);
            richTextBox2.Clear();
            client.BeginSend(message, 0, message.Length, SocketFlags.None,
                         new AsyncCallback(SendData), client);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            client.Close();
            richTextBox3.AppendText ("Disconnected \n");
        }

        private void Connected(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                richTextBox3.Invoke(this.myDelegate2, new Object[] { "Connected to: " + client.RemoteEndPoint.ToString() +"\n"});
                client.BeginReceive(data, 0, size, SocketFlags.None,
                              new AsyncCallback(ReceiveData), client);
                button2.Invoke(this.myDelegate3, new Object[] { });
            }
            catch (SocketException)
            {
                richTextBox3.Invoke(this.myDelegate2, new Object[] { "Error connecting \n"});
            }
        }

        private void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            richTextBox1.Invoke(this.myDelegate, new Object[]{stringData+"\n"});
        }

        private void SendData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int sent = remote.EndSend(iar);
            remote.BeginReceive(data, 0, size, SocketFlags.None,
                          new AsyncCallback(ReceiveData), remote);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = comboBox1.SelectedItem.ToString();
        }

    }
}


Async Tcp background:
 http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm

reference:
http://forums.codeguru.com/showthread.php?509248-How-to-run-a-very-long-SQL-statement
http://msdn.microsoft.com/en-us/library/5w7b7x5f(v=vs.110).aspx
http://www.java2s.com/Code/CSharp/Network/AsyncTcpServer.htm
http://www.java2s.com/Code/CSharp/Network/AsyncTcpClient.htm

No comments:

Post a Comment