protocol buffer是什么就不多解释了,谷歌一大堆。直接上代码:DGShowMsg.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace SocketService
{
    public delegate void DGShowMsg(string Msg);
}ConnectionClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using Google.ProtocolBuffers;namespace SocketService
{
    public class ConnectionClient
    {
        Socket sokMsg;
        DGShowMsg dgShowMsg;// 显示文字的委托
        DGShowMsg reMoveConnection;//断开连接
        Thread th;        public ConnectionClient(Socket sokMsg, DGShowMsg dgShowMsg, DGShowMsg reMoveConnection)
        {
            this.sokMsg = sokMsg;
            this.dgShowMsg = dgShowMsg;
            this.reMoveConnection = reMoveConnection;
            this.th = new Thread(RecMsg);
            this.th.IsBackground = true;
            this.th.Start();
        }
        public ConnectionClient() { }        bool isRec = true;
        /// <summary>
        /// 监听客户端发过来的消息
        /// </summary>
        void RecMsg()
        {
            while (isRec)
            {
                int length = 0;
                string strMsg = null;
                if (sokMsg.Available != 0)
                {
                    int len = sokMsg.Available;
                    byte[] msgArr = new byte[len];
                    length = sokMsg.Receive(msgArr);
                    MyRequest request = MyRequest.ParseFrom(msgArr);
                    strMsg += string.Format("接受到的数据有:{0},{1},{2}", request.Version, request.Name, request.Website);
                    dgShowMsg(strMsg.ToString());
                }
            }
        }
        /// <summary>
        /// 给客户端发送消息
        /// </summary>
        /// <param name="strMsg"></param>
        public void Send(string strMsg)
        {
            byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
            sokMsg.Send(arrMsg);
        }
    }
}server.csusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.ProtocolBuffers;
using System.Net;
using System.Net.Sockets;
using System.Threading;namespace SocketService
{
    public partial class Service : Form
    {
        public Service()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;//关闭跨线程检查
        }
        Socket sokWatch = null;//负责监听请求
        Thread thWatch = null;//负责监听请求的线程        private void button3_Click(object sender, EventArgs e)
        {
            sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress address = IPAddress.Parse(txtIp.Text.Trim()); //创建IP对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim())); //绑定
            sokWatch.Bind(endpoint);
            sokWatch.Listen(10);
            thWatch = new Thread(StartWatch);
            thWatch.IsBackground = true;
            thWatch.Start();
            textBox1.AppendText("服务器启动成功!\r\n");
        }
        Dictionary<string, ConnectionClient> diction = new Dictionary<string, ConnectionClient>(); //定义字典        bool isWatch = true;        ///<summary>
        /// 监听连接端口
        /// </summary>
        void StartWatch()
        {
            while (isWatch)
            {
                Socket sokMsg = sokWatch.Accept(); //监听到请求
                ConnectionClient connection = new ConnectionClient(sokMsg, ShowMsg, RemoveClientConnection);
                diction.Add(sokMsg.RemoteEndPoint.ToString(), connection);
                cboClient.Items.Add(sokMsg.RemoteEndPoint.ToString());
                ShowMsg(sokMsg.RemoteEndPoint.ToString() + "连接成功...");
            }
        }
        ///<summary>
        /// 显示文字
        /// </summary>
        /// <param name="msgStr"></param>
        /// 
        public void ShowMsg(string msgStr)
        {
            textBox1.AppendText(msgStr);
        }
        ///<summary>
        /// 停止监听
        /// </summary>
        /// <param name="key"></param>
        public void RemoveClientConnection(string key)
        {
            if (diction.ContainsKey(key))
            {
                diction.Remove(key);
                cboClient.Items.Remove(key);
            }
        }        private void button1_Click(object sender, EventArgs e)
        {
            string key = cboClient.Text;
            if (!string.IsNullOrEmpty(key))
            {
                diction[key].Send(textBox2.Text.Trim());
                textBox2.Text = "";
            }
            else
            {
                MessageBox.Show("请选择客户端");
            }
        }
    }
}client.csusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using SocketService;
using Google.ProtocolBuffers;namespace SocketClient
{
    public partial class Client : Form
    {
        public Client()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }
        Socket sokClient = null;
        Thread thClient = null;
        bool isRec = true;//是否循环接受服务端数据        private void btnConnection_Click(object sender, EventArgs e)
        {
            sokClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
            sokClient.Connect(endpoint);
            thClient = new Thread(ReceiveMsg);
            thClient.IsBackground = true;
            thClient.SetApartmentState(ApartmentState.STA);
            thClient.Start();
        }
        void ReceiveMsg()
        {
            while (isRec)
            {
                byte[] msgArr = new byte[4];
                int length = 0;
                length = sokClient.Receive(msgArr);
                string str = System.Text.Encoding.UTF8.GetString(msgArr, 0, length);
                textBox2.AppendText(str + "\r\n");
            }
        }
        ///<soummary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            //构造数据
            try
            {
                //构造MyData                MyData.Builder myDataBuilder = MyData.CreateBuilder();
                myDataBuilder.Resume = "我的个人简介";
                MyData myData = myDataBuilder.Build();
                //构造MyRequest
                MyRequest.Builder myRequestBuilder = MyRequest.CreateBuilder();
                myRequestBuilder.Version = 1;
                myRequestBuilder.Name = "构造";
                myRequestBuilder.Website = "www.monkeys.com";
                myRequestBuilder.Data = myData.ToByteString();
                MyRequest myRequest = myRequestBuilder.Build();
                byte[] byteRequest = myRequest.ToByteArray();
                sokClient.Send(byteRequest);            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}Mydata,Myrequest,Myresponse 三个分别是proto文件生成的cs文件,模板如下
message MyData {
//个人简介
optional string resume = 1[default="I'm goodman"];
}
message MyRequest {
//版本号
required int32 version = 1;
//姓名
required string name = 2;
//个人网站
optional string website = 3[default="http://www.paotiao.com/"];
//附加数据
optional bytes data = 4;
}
message MyResponse {
//版本号
required int32 version = 1;
//响应结果
required int32 result = 2;
}
需要注意的是:Client发送的byte只能用buffer自带的方法转换,而不能用Encoding.UTF8/Default.GetString/Getbytes方法转。