c# socket 同步开发小例子

来源:互联网 发布:数据存储以什么为单位 编辑:程序博客网 时间:2024/04/30 06:30

这两天在研究socket开发看了网上有很多这样的例子,也写了一个类似的程序希望大家共同交流,环境vs2005

 

以下是服务器端代码

服务器端界面

form1.cs文件

 

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.IO;using System.Net;using System.Threading;using System.Collections;namespace SocketServer{    delegate void Myhandle(string s);       public partial class Form1 : Form    {        Socket sock;        Thread newthread;        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            this.button1.Enabled = false;                      //启动独立线程开始侦听            newthread = new Thread(startListenSocket);            newthread.Start();                               }                public void setString(string s)        {            this.textBox1.Text += s;        }        public void startListenSocket()        {            try            {                int port = 3388;                IPAddress ip = IPAddress.Parse("127.0.0.1");                IPEndPoint ipe = new IPEndPoint(ip, port);                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                sock.Bind(ipe);                sock.Listen(2);                while (true)                {                    Socket tempsocket = sock.Accept();                    byte[] restrs = new byte[1024];                    int recount = tempsocket.Receive(restrs);                    string str = "";                    str = Encoding.Default.GetString(restrs, 0, recount);
                    //判断结尾是否是*号 如果是表示传送完毕                    while (str.Substring(str.Length - 1, 1) != "*")                    {                        int count = tempsocket.Receive(restrs);                        str = Encoding.Default.GetString(restrs, 0, count);                        str = str.Trim();                    }                    byte[] anstr = Encoding.Default.GetBytes("客户端我收完了");                    tempsocket.Send(anstr);                    Myhandle my = new Myhandle(setString);                    this.Invoke(my, new object[] { str });                }            }            catch(Exception e)            {                MessageBox.Show(e.Message);            }        }    }}

 

form1.designer.cs文件

namespace SocketServer{ partial class Form1 { ///

/// 必需的设计器变量。 /// private System.ComponentModel.IContainer components = null; /// /// 清理所有正在使用的资源。 /// /// 如果应释放托管资源,为 true;否则为 false。 protected override void Dispose(bool disposing) { if (sock != null) { newthread.Abort(); sock.Close(); } if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// 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; }}

   客户端代码

客户端界面

form1.cs文件

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.IO;using System.Net.Sockets;using System.Net;using System.Threading;namespace socketClint{    delegate void reHandle(string s);    public partial class client : Form    {        public client()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            try            {                int port = 3388;                IPAddress ip = IPAddress.Parse("127.0.0.1");                IPEndPoint ipe = new IPEndPoint(ip, port);                Socket clsoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                clsoc.Connect(ipe);                string sendstr = this.textBox1.Text+"*";//以*号作为结尾,也可以用其他方式判断传送结束                byte[] sstr = Encoding.Default.GetBytes(sendstr);                clsoc.Send(sstr);                Thread newth = new Thread(result);                newth.Start((object)clsoc);                      }            catch(Exception ex)            {                MessageBox.Show(ex.Message);            }        }        private void result(object obj)        {            Socket s = (Socket)obj;            byte[] restrs = new byte[1024];            int recount=s.Receive(restrs);            string str = Encoding.Default.GetString(restrs);            reHandle myhandle = new reHandle(re);            this.Invoke(myhandle, new object[] { str });            s.Close();        }        private void re(string s)        {            this.textBox1.Text = s;        }    }}