1. 程式人生 > >簡單的TCP連線Server和Client

簡單的TCP連線Server和Client

    我們的一款unity開發的遊戲,之前一直在android上測試,這幾天我做了遊戲的Windows Phone 8版本匯出工作,經過一週摸索,終於成功打出了可以在wp8手機上正常執行的版本。

    wp8的.net庫是Silverlight的一個子集,很多.net 2.0的語法它不支援,socket的很多屬性和方法就是這樣。由於我是第一次搞tcp連線,摸索的時候也走了些彎路,其間寫了一個簡單的基於.net 2.0的tcp server和tcp client做學習、測試用。



下面是主要的程式碼,完整程式碼和工程我傳到了csdn的下載頻道,請點選開啟下載

    TCPClient

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;

namespace TCPClient
{
    public partial class TCPClient : Form
    {
        string ipAddress = "127.0.0.1";
        int port = 9527;
        Socket clientSocket;
        byte[] buffer = new byte[512 * 1024];

        public TCPClient()
        {
            InitializeComponent();
        }

        private void Form_Load(object sender, EventArgs e)
        {
            ipAddressBox.Text = ipAddress;
            portBox.Text = port.ToString();
        }
        void Form_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (clientSocket != null)
            {
                clientSocket.Close();
                clientSocket = null;
            }
        }

        private void connectButton_Click(object sender, EventArgs e)
        {
            try
            {
                ipAddress = ipAddressBox.Text;
                port = int.Parse(portBox.Text);

                IPAddress remoteIP = IPAddress.Parse(ipAddress);
                IPEndPoint remoteEP = new IPEndPoint(remoteIP, port);

                if (clientSocket != null)
                    clientSocket.Close();

                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(remoteEP);
                AppendContent(string.Format("connect {0}:{1}", ipAddress, port));
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        void sendButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(inputBox.Text))
                {
                    MessageBox.Show("please input content.");
                    return;
                }

                if (clientSocket == null || !clientSocket.Connected)
                {
                    MessageBox.Show("please connect first.");
                    return;
                }

                AppendContent(inputBox.Text);
                byte[] bytes = Encoding.UTF8.GetBytes(inputBox.Text);
                inputBox.Text = "";

                clientSocket.Send(bytes);

                int length = clientSocket.Receive(buffer);
                string receivedContent = Encoding.UTF8.GetString(buffer, 0, length);
                AppendContent(receivedContent);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void AppendContent(string str)
        {
            if (string.IsNullOrEmpty(contentBox.Text))
                contentBox.Text = str;
            else
                contentBox.Text = string.Format("{0}\n{1}", contentBox.Text, str);
        }
    }
}

    TCPServer
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TCPServer
{
    class Program
    {
        const int port = 9527;
        const int backlog = 20;

        static void Main(string[] args)
        {
            // create the socket
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // bind the listening socket to the port
            IPAddress hostIP = IPAddress.Any;
            IPEndPoint ep = new IPEndPoint(hostIP, port);
            serverSocket.Bind(ep);

            // start listening
            serverSocket.Listen(backlog);
            Console.WriteLine("listen on port:{0}", port);

            while (true)
            {
                // sync accept a connect
                Socket clientSocket = serverSocket.Accept();

                // create a thread to process the connect
                ConnectService connectService = new ConnectService(clientSocket);
                Thread thread = new Thread(new ThreadStart(connectService.Process));
                thread.Start();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TCPServer
{
    class ConnectService
    {
        private Socket clientSocket = null;

        public ConnectService(Socket socket)
        {
            clientSocket = socket;
        }

        public void Process()
        {
            byte[] buffer = new byte[512 * 1024];
            string content;

            string ipAddr = ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString();
            Console.WriteLine("a new connect from:{0}", ipAddr);

            try
            {
                int received = 0;
                while ((received = clientSocket.Receive(buffer)) != 0)
                {
                    content = Encoding.UTF8.GetString(buffer, 0, received);
                    Console.WriteLine("received:{0}", content);

                    content = string.Format("server echo:{0}", content);
                    buffer = Encoding.UTF8.GetBytes(content);
                    clientSocket.Send(buffer);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            clientSocket.Close();
            Console.WriteLine("connect from {0} closed.", ipAddr);
        }
    }
}