博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Socket 同步编程的一个简单例子,适合初学者

Posted on 2008-11-13 10:38  strong.xu  阅读(685)  评论(0编辑  收藏  举报

服务器端的界面编码:

namespace MySocketSameServer
{
    partial class Server  
    {  
        /// <SUMMARY>  
        /// 必需的设计器变量。  
        /// </SUMMARY>  
        private System.ComponentModel.IContainer components = null;  
 
        /// <SUMMARY>  
        /// 清理所有正在使用的资源。  
        /// </SUMMARY>  
        /// <PARAM name="disposing">如果应释放托管资源,为 true;否则为 false。</PARAM>  
        protected override void Dispose(bool disposing)  
        {  
             
            if (_serverSock != null)  
            {  
                _serverNewthread.Abort();  
                _serverSock.Close();  
            }  
            if (disposing && (components != null))  
            {  
                components.Dispose();  
            }  
            base.Dispose(disposing);  
        } 
        
        #region Windows 窗体设计器生成的代码  
 
        /// <SUMMARY>  
        /// 设计器支持所需的方法 - 不要  
        /// 使用代码编辑器修改此方法的内容。  
        /// </SUMMARY>  
        private void InitializeComponent()  
        {  
            this.button1 = new System.Windows.Forms.Button();  
            this.textBox1 = new System.Windows.Forms.TextBox();  
            this.SuspendLayout();  
            //   
            // button1  
            //   
            this.button1.Location = new System.Drawing.Point(29, 12);  
            this.button1.Name = "button1";  
            this.button1.Size = new System.Drawing.Size(75, 23);  
            this.button1.TabIndex = 0;  
            this.button1.Text = "侦听开始";  
            this.button1.UseVisualStyleBackColor = true;  
            this.button1.Click += new System.EventHandler(this.button1_Click);  
            //   
            // textBox1  
            //   
            this.textBox1.Location = new System.Drawing.Point(29, 41);  
            this.textBox1.Multiline = true;  
            this.textBox1.Name = "textBox1";  
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;  
            this.textBox1.Size = new System.Drawing.Size(574, 220);  
            this.textBox1.TabIndex = 1;  
            //   
            // Form1  
            //   
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);  
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;  
            this.ClientSize = new System.Drawing.Size(615, 273);  
            this.Controls.Add(this.textBox1);  
            this.Controls.Add(this.button1);  
            this.Name = "Form1";  
            this.Text = "server";  
            this.ResumeLayout(false);  
            this.PerformLayout();  
 
        } 
 
        #endregion  
 
        private System.Windows.Forms.Button button1;  
        private System.Windows.Forms.TextBox textBox1;  
    }  
}  
服务器段的程序:

 

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.Sockets;
using System.Threading;
using System.Net;

namespace MySocketSameServer
{
    delegate void Myhandle(string s);  
     
    public partial class Server : Form  
    {  
        Socket _serverSock;  
        Thread _serverNewthread;  
        public Server()  
        {  
            InitializeComponent();
        }  
 
        private void button1_Click(object sender, EventArgs e)  
        {  
            this.button1.Enabled = false;  
            
            //启动独立线程开始侦听  
            _serverNewthread = new Thread(StartListenSocket);  
            _serverNewthread.Start();  
             
              
        }  
          
        public void SetString(string s)  
        {  
            this.textBox1.Text += s;  
        }  

        public void StartListenSocket()  
        {  
            try
            {
               
                IPHostEntry iphostEntry = Dns.GetHostByName(Dns.GetHostName());
                IPAddress serverIp = iphostEntry.AddressList[0];

                int serverPort = 3388;  
                //IPAddress serverIp = IPAddress.Parse("192.168.8.104");  
                IPEndPoint serverIpEndPoint = new IPEndPoint(serverIp, serverPort);  
                _serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _serverSock.Bind(serverIpEndPoint);
                _serverSock.Listen(10); 
 
                while (true)
                {  
                    //下面这句决定是同步Socket变成,如果是异步应该是BeginAccept
                    //由于是异步
                    Socket receiveClientSocket = _serverSock.Accept();//socket的底层代码已经经过了三次握手,建立了连接,该语句是保存连接后客户端的socket
                    byte[] receiveBuffer = new byte[1024];//在内存中开辟一个1024字节大小的空间,来保存接受数据 
                    int receiveByteCount = receiveClientSocket.Receive(receiveBuffer);//从绑定的 Socket 套接字接收数据,将数据存入接收缓冲区。返回值是接收到的字节数.  
                    string receiveStr = string.Empty;
                    receiveStr = Encoding.Default.GetString(receiveBuffer, 0, receiveByteCount);
                    while (receiveStr.Substring(receiveStr.Length - 1, 1) != "*")  //判断结尾是否是*号 如果是表示传送完毕
                    {  
                        int count = receiveClientSocket.Receive(receiveBuffer);  
                        receiveStr += Encoding.Default.GetString(receiveBuffer, 0, count);  
                        receiveStr = receiveStr.Trim();  
                    }  
                    byte[] sendBuffer = Encoding.Default.GetBytes("客户端我收完了");  
                    receiveClientSocket.Send(sendBuffer);
                    //receiveClientSocket.Shutdown(SocketShutdown.Both);
                    //receiveClientSocket.Close(10);
                    Myhandle my = new Myhandle(SetString);  
                    this.Invoke(my, new object[] { receiveStr });  
                }  
            }  
            catch(Exception e)  
            {  
                MessageBox.Show(e.Message);  
            }  
        }  
    } 
}

 

客户端的界面代码:

 

namespace MySocketSameClient
{
    partial class Client
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(378, 341);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // textBox1
            //
            this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.textBox1.Location = new System.Drawing.Point(0, 0);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(558, 269);
            this.textBox1.TabIndex = 1;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(558, 406);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
    }
}

客户端的程序:

 

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;
using System.Threading;

namespace MySocketSameClient
{
    delegate void reHandle(string s);
    public partial class Client : Form
    {
        public Client()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int serverPort = 3388;
                IPAddress serverIp = IPAddress.Parse("192.168.8.104");
                IPEndPoint serverIpEndPoint = new IPEndPoint(serverIp, serverPort);
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(serverIpEndPoint);
                string sendStr = this.textBox1.Text + "*";//以*号作为结尾,也可以用其他方式判断传送结束  
                byte[] sendByte = Encoding.Default.GetBytes(sendStr);
                clientSocket.Send(sendByte);               
                Thread clientNewThread = new Thread(result);
                clientNewThread.Start((object)clientSocket);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void result(object obj)
        {
            Socket clientSocket = (Socket)obj;
            byte[] receiveByte = new byte[1024];
            int receiveCount = clientSocket.Receive(receiveByte);
            string receiveStr = Encoding.Default.GetString(receiveByte);
            reHandle myhandle = new reHandle(re);
            this.Invoke(myhandle, new object[] { receiveStr });
            clientSocket.Close();
        }
        private void re(string s)
        {
            this.textBox1.Text = s;
        }
    } 
   
}