简单的TCP连接Server和Client

    我们的一款unity开发的游戏,之前一直在android上测试,这几天我做了游戏的Windows Phone 8版本导出工作,经过一周摸索,终于成功打出了可以在wp8手机上正常运行的版本。

    wp8的.net库是Silverlight的一个子集,很多.net 2.0的语法它不支持,socket的很多属性和方法就是这样。由于我是第一次搞tcp连接,摸索的时候也走了些弯路,其间写了一个简单的基于.net 2.0的tcp server和tcp client做学习、测试用。

简单的TCP连接Server和Client_第1张图片

简单的TCP连接Server和Client_第2张图片

下面是主要的代码,完整代码和工程我传到了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);
        }
    }
}


你可能感兴趣的:(网络)