Socket编程

客户端

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets ;
using System.Threading ;

namespace sock_user
{
    
/// <summary>
    
/// Form1 的摘要说明。
    
/// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.Label label2;
        
private System.Windows.Forms.Label label3;
        
private System.Windows.Forms.Label label4;
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.TextBox textBox2;
        
private System.Windows.Forms.GroupBox groupBox1;
        
private System.Windows.Forms.RichTextBox richTextBox1;
        
private System.Windows.Forms.RichTextBox richTextBox2;
        
private System.Windows.Forms.ListBox listBox1;
        
private System.Windows.Forms.Button button1;
        
private System.Windows.Forms.Button button2;
        
private System.Windows.Forms.Button button3;
        
/// <summary>
        
/// 必需的设计器变量。
        
/// </summary>
        private IPAddress myIP=IPAddress.Parse("127.0.0.1");  //把字符串转换为IPAddress格式;
        private IPEndPoint MyServer;
        
private Socket connectsock;
        
private bool check=true;
        
private System.ComponentModel.Container components = null;

        
public Form1()
        {
            
//
            
// Windows 窗体设计器支持所必需的
            
//
            InitializeComponent();

            
//
            
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            
//
        }

        
/// <summary>
        
/// 清理所有正在使用的资源。
        
/// </summary>
        protected override void Dispose( bool disposing )
        {
            
if( disposing )
            {
                
if (components != null
                {
                    components.Dispose();
                }
            }
            
base.Dispose( disposing );
        }

        
#region Windows 窗体设计器生成的代码
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>
        private void InitializeComponent()
        {
            
this.label1 = new System.Windows.Forms.Label();
            
this.label2 = new System.Windows.Forms.Label();
            
this.label3 = new System.Windows.Forms.Label();
            
this.label4 = new System.Windows.Forms.Label();
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.textBox2 = new System.Windows.Forms.TextBox();
            
this.groupBox1 = new System.Windows.Forms.GroupBox();
            
this.listBox1 = new System.Windows.Forms.ListBox();
            
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            
this.button1 = new System.Windows.Forms.Button();
            
this.button2 = new System.Windows.Forms.Button();
            
this.button3 = new System.Windows.Forms.Button();
            
this.groupBox1.SuspendLayout();
            
this.SuspendLayout();
            
// 
            
// label1
            
// 
            this.label1.Location = new System.Drawing.Point(212);
            
this.label1.Name = "label1";
            
this.label1.Size = new System.Drawing.Size(6016);
            
this.label1.TabIndex = 0;
            
this.label1.Text = "服务器IP:";
            
// 
            
// label2
            
// 
            this.label2.Location = new System.Drawing.Point(248);
            
this.label2.Name = "label2";
            
this.label2.Size = new System.Drawing.Size(6016);
            
this.label2.TabIndex = 0;
            
this.label2.Text = "请求端口:";
            
// 
            
// label3
            
// 
            this.label3.Location = new System.Drawing.Point(286);
            
this.label3.Name = "label3";
            
this.label3.Size = new System.Drawing.Size(6016);
            
this.label3.TabIndex = 0;
            
this.label3.Text = "接受信息:";
            
// 
            
// label4
            
// 
            this.label4.Location = new System.Drawing.Point(2158);
            
this.label4.Name = "label4";
            
this.label4.Size = new System.Drawing.Size(6016);
            
this.label4.TabIndex = 0;
            
this.label4.Text = "发送信息:";
            
// 
            
// textBox1
            
// 
            this.textBox1.Location = new System.Drawing.Point(668);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.Size = new System.Drawing.Size(9421);
            
this.textBox1.TabIndex = 1;
            
this.textBox1.Text = "";
            
// 
            
// textBox2
            
// 
            this.textBox2.Location = new System.Drawing.Point(6644);
            
this.textBox2.Name = "textBox2";
            
this.textBox2.Size = new System.Drawing.Size(9421);
            
this.textBox2.TabIndex = 1;
            
this.textBox2.Text = "";
            
// 
            
// groupBox1
            
// 
            this.groupBox1.Controls.Add(this.listBox1);
            
this.groupBox1.Location = new System.Drawing.Point(1622);
            
this.groupBox1.Name = "groupBox1";
            
this.groupBox1.Size = new System.Drawing.Size(33266);
            
this.groupBox1.TabIndex = 2;
            
this.groupBox1.TabStop = false;
            
this.groupBox1.Text = "客户状态";
            
// 
            
// listBox1
            
// 
            this.listBox1.ItemHeight = 12;
            
this.listBox1.Location = new System.Drawing.Point(412);
            
this.listBox1.Name = "listBox1";
            
this.listBox1.Size = new System.Drawing.Size(32252);
            
this.listBox1.TabIndex = 0;
            
// 
            
// richTextBox1
            
// 
            this.richTextBox1.Location = new System.Drawing.Point(6682);
            
this.richTextBox1.Name = "richTextBox1";
            
this.richTextBox1.Size = new System.Drawing.Size(42664);
            
this.richTextBox1.TabIndex = 3;
            
this.richTextBox1.Text = "";
            
// 
            
// richTextBox2
            
// 
            this.richTextBox2.Location = new System.Drawing.Point(66156);
            
this.richTextBox2.Name = "richTextBox2";
            
this.richTextBox2.Size = new System.Drawing.Size(42664);
            
this.richTextBox2.TabIndex = 3;
            
this.richTextBox2.Text = "";
            
// 
            
// button1
            
// 
            this.button1.Location = new System.Drawing.Point(18240);
            
this.button1.Name = "button1";
            
this.button1.TabIndex = 4;
            
this.button1.Text = "连接";
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
// 
            
// button2
            
// 
            this.button2.Location = new System.Drawing.Point(128240);
            
this.button2.Name = "button2";
            
this.button2.TabIndex = 4;
            
this.button2.Text = "发送信息";
            
this.button2.Click += new System.EventHandler(this.button2_Click);
            
// 
            
// button3
            
// 
            this.button3.Location = new System.Drawing.Point(240240);
            
this.button3.Name = "button3";
            
this.button3.TabIndex = 4;
            
this.button3.Text = "关闭连接";
            
this.button3.Click += new System.EventHandler(this.button3_Click);
            
// 
            
// Form1
            
// 
            this.AutoScaleBaseSize = new System.Drawing.Size(614);
            
this.ClientSize = new System.Drawing.Size(530281);
            
this.Controls.Add(this.button1);
            
this.Controls.Add(this.richTextBox1);
            
this.Controls.Add(this.groupBox1);
            
this.Controls.Add(this.textBox1);
            
this.Controls.Add(this.label1);
            
this.Controls.Add(this.label2);
            
this.Controls.Add(this.label3);
            
this.Controls.Add(this.label4);
            
this.Controls.Add(this.textBox2);
            
this.Controls.Add(this.richTextBox2);
            
this.Controls.Add(this.button2);
            
this.Controls.Add(this.button3);
            
this.Name = "Form1";
            
this.Text = "客户端";
            
this.groupBox1.ResumeLayout(false);
            
this.ResumeLayout(false);

        }
        
#endregion

        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>
        [STAThread]
        
static void Main() 
        {
            Application.Run(
new Form1());
        }

        
private void Form1_Load(object sender, System.EventArgs e)
        {
        
        }

        
private void button1_Click(object sender, System.EventArgs e)
        {
            
string IpStr="";
            
try
            {
                
//把textBox1.Text输入的转换为IP地址
                IPHostEntry IPHost=Dns.Resolve(this.textBox1.Text);
                
string teststr=IPHost.HostName;
                IPAddress[] addr
=IPHost.AddressList;
                
for(int i=0;i<addr.Length;i++)
                {
                    IpStr
+=addr[i];
                }
            }
            
catch(Exception er)
            {
                MessageBox.Show(er.Message);
            }
            
//IP地址字符串转换为IPAddress格式;
            myIP=IPAddress.Parse (IpStr);

            
try
            {
                MyServer
=new IPEndPoint(myIP,Int32.Parse (textBox2.Text ));
                connectsock
=new Socket(AddressFamily.InterNetwork ,SocketType.Stream ,ProtocolType.Tcp );
                connectsock.Connect (MyServer);
                
if(!connectsock.Connected)
                {
                    MessageBox.Show(
"连接主机失败!");
                }
                
else
                {
                    listBox1.Items.Add (
"与主机"+textBox1.Text +"端口"+textBox2.Text+"连接成功! ");
                    Thread thread
=new Thread (new ThreadStart (receive));
                    thread.Start ();
                }
            }
            
catch(Exception ee)
            {
                MessageBox.Show (ee.Message );
            }

        }

        
private void button2_Click(object sender, System.EventArgs e)
        {
            
try
            {
                Byte[] sendbyte
=new Byte [64];
                
string send=richTextBox2.Text +" ";
                
//生成NetworkStream实例,用于发送基础数据流。


                NetworkStream netstream
=new NetworkStream (connectsock);
                sendbyte
=System.Text .Encoding .BigEndianUnicode .GetBytes (send.ToCharArray ());
                netstream.Write (sendbyte,
0,sendbyte.Length );//向socket服务器发送信息。
                netstream.Flush ();
            }
            
catch
            {
                MessageBox.Show (
"连接没有建立!无法发送!");
            }

        }

        
private void button3_Click(object sender, System.EventArgs e)
        {
            
try
            {
                connectsock.Close ();
//断开连接。
                listBox1.Items .Add ("与主机"+textBox1.Text +"端口"+textBox2.Text +"断开连接! ");
            }
            
catch
            {
                MessageBox.Show (
"连接没有建立!断开无效!");
            }

        }

        
private void receive()
        {
            
while(true)
            {
                Byte[] Rec
=new byte [64];
                NetworkStream netstream
=new NetworkStream (connectsock);
                netstream.Read (Rec,
0,Rec.Length );//读取客户发送来的信息。
                string RecMessage=System.Text .Encoding .BigEndianUnicode .GetString (Rec);
                richTextBox1.AppendText (RecMessage
+" ");//写入到接收信息栏中。
            }
        }


    }
}

 服务端

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets ;
using System.Threading ;

namespace mySocket
{
    
/// <summary>
    
/// Form1 的摘要说明。
    
/// </summary>
    public class StateObject : System.Windows.Forms.Form
    {
        
#region
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.Label label2;
        
private System.Windows.Forms.Label label3;
        
private System.Windows.Forms.Label label4;
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.TextBox textBox2;
        
private System.Windows.Forms.GroupBox groupBox1;
        
private System.Windows.Forms.RichTextBox richTextBox1;
        
private System.Windows.Forms.RichTextBox richTextBox2;
        
private System.Windows.Forms.ListBox listBox1;
        
private System.Windows.Forms.Button button1;
        
private System.Windows.Forms.Button button2;
        
private System.Windows.Forms.Button button3;
        
#endregion
        
/// <summary>
        
/// 必需的设计器变量。
        
/// </summary>
        private IPAddress myIP=IPAddress.Parse("127.0.0.1");  //把字符串转换为IPAddress格式;
        private IPEndPoint MyServer;
        
private Socket sock;
        
private bool check=true;
        
private Socket accsock;
        
/// <summary>
        
/// 
        
/// </summary>
        private System.ComponentModel.Container components = null;

        
public StateObject()
        {
            
//
            
// Windows 窗体设计器支持所必需的
            
//
            InitializeComponent();

            
//
            
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            
//
        }

        
/// <summary>
        
/// 清理所有正在使用的资源。
        
/// </summary>
        protected override void Dispose( bool disposing )
        {
            
if( disposing )
            {
                
if (components != null
                {
                    components.Dispose();
                }
            }
            
base.Dispose( disposing );
        }

        
#region Windows 窗体设计器生成的代码
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>
        private void InitializeComponent()
        {
            
this.label1 = new System.Windows.Forms.Label();
            
this.label2 = new System.Windows.Forms.Label();
            
this.label3 = new System.Windows.Forms.Label();
            
this.label4 = new System.Windows.Forms.Label();
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.textBox2 = new System.Windows.Forms.TextBox();
            
this.groupBox1 = new System.Windows.Forms.GroupBox();
            
this.listBox1 = new System.Windows.Forms.ListBox();
            
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            
this.button1 = new System.Windows.Forms.Button();
            
this.button2 = new System.Windows.Forms.Button();
            
this.button3 = new System.Windows.Forms.Button();
            
this.groupBox1.SuspendLayout();
            
this.SuspendLayout();
            
// 
            
// label1
            
// 
            this.label1.Location = new System.Drawing.Point(212);
            
this.label1.Name = "label1";
            
this.label1.Size = new System.Drawing.Size(6016);
            
this.label1.TabIndex = 0;
            
this.label1.Text = "服务器IP:";
            
// 
            
// label2
            
// 
            this.label2.Location = new System.Drawing.Point(18414);
            
this.label2.Name = "label2";
            
this.label2.Size = new System.Drawing.Size(6016);
            
this.label2.TabIndex = 0;
            
this.label2.Text = "监听端口:";
            
// 
            
// label3
            
// 
            this.label3.Location = new System.Drawing.Point(260);
            
this.label3.Name = "label3";
            
this.label3.Size = new System.Drawing.Size(6016);
            
this.label3.TabIndex = 0;
            
this.label3.Text = "接受信息:";
            
// 
            
// label4
            
// 
            this.label4.Location = new System.Drawing.Point(2120);
            
this.label4.Name = "label4";
            
this.label4.Size = new System.Drawing.Size(6016);
            
this.label4.TabIndex = 0;
            
this.label4.Text = "发送信息:";
            
// 
            
// textBox1
            
// 
            this.textBox1.Location = new System.Drawing.Point(668);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.Size = new System.Drawing.Size(9421);
            
this.textBox1.TabIndex = 1;
            
this.textBox1.Text = "";
            
// 
            
// textBox2
            
// 
            this.textBox2.Location = new System.Drawing.Point(25812);
            
this.textBox2.Name = "textBox2";
            
this.textBox2.Size = new System.Drawing.Size(6621);
            
this.textBox2.TabIndex = 1;
            
this.textBox2.Text = "";
            
// 
            
// groupBox1
            
// 
            this.groupBox1.Controls.Add(this.listBox1);
            
this.groupBox1.Location = new System.Drawing.Point(8198);
            
this.groupBox1.Name = "groupBox1";
            
this.groupBox1.Size = new System.Drawing.Size(330110);
            
this.groupBox1.TabIndex = 2;
            
this.groupBox1.TabStop = false;
            
this.groupBox1.Text = "服务器状态";
            
// 
            
// listBox1
            
// 
            this.listBox1.ItemHeight = 12;
            
this.listBox1.Location = new System.Drawing.Point(412);
            
this.listBox1.Name = "listBox1";
            
this.listBox1.Size = new System.Drawing.Size(32488);
            
this.listBox1.TabIndex = 0;
            
// 
            
// richTextBox1
            
// 
            this.richTextBox1.Location = new System.Drawing.Point(6640);
            
this.richTextBox1.Name = "richTextBox1";
            
this.richTextBox1.Size = new System.Drawing.Size(27664);
            
this.richTextBox1.TabIndex = 3;
            
this.richTextBox1.Text = "";
            
// 
            
// richTextBox2
            
// 
            this.richTextBox2.Location = new System.Drawing.Point(66110);
            
this.richTextBox2.Name = "richTextBox2";
            
this.richTextBox2.Size = new System.Drawing.Size(27464);
            
this.richTextBox2.TabIndex = 3;
            
this.richTextBox2.Text = "";
            
// 
            
// button1
            
// 
            this.button1.Location = new System.Drawing.Point(18312);
            
this.button1.Name = "button1";
            
this.button1.TabIndex = 4;
            
this.button1.Text = "开始监听";
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
// 
            
// button2
            
// 
            this.button2.Location = new System.Drawing.Point(128312);
            
this.button2.Name = "button2";
            
this.button2.TabIndex = 4;
            
this.button2.Text = "发送信息";
            
this.button2.Click += new System.EventHandler(this.button2_Click);
            
// 
            
// button3
            
// 
            this.button3.Location = new System.Drawing.Point(240312);
            
this.button3.Name = "button3";
            
this.button3.TabIndex = 4;
            
this.button3.Text = "停止监听";
            
this.button3.Click += new System.EventHandler(this.button3_Click);
            
// 
            
// StateObject
            
// 
            this.AutoScaleBaseSize = new System.Drawing.Size(614);
            
this.ClientSize = new System.Drawing.Size(372340);
            
this.Controls.Add(this.button1);
            
this.Controls.Add(this.richTextBox1);
            
this.Controls.Add(this.groupBox1);
            
this.Controls.Add(this.textBox1);
            
this.Controls.Add(this.label1);
            
this.Controls.Add(this.label2);
            
this.Controls.Add(this.label3);
            
this.Controls.Add(this.label4);
            
this.Controls.Add(this.textBox2);
            
this.Controls.Add(this.richTextBox2);
            
this.Controls.Add(this.button2);
            
this.Controls.Add(this.button3);
            
this.Name = "StateObject";
            
this.Text = "服务器";
            
this.Load += new System.EventHandler(this.StateObject_Load);
            
this.groupBox1.ResumeLayout(false);
            
this.ResumeLayout(false);

        }
        
#endregion

        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>
        [STAThread]
        
static void Main() 
        {
            Application.Run(
new StateObject());
        }

        
private void StateObject_Load(object sender, System.EventArgs e)
        {
        
        }

        
private void button1_Click(object sender, System.EventArgs e)
        {
            
string IpStr="";
            
try
            {
                
//把textBox1.Text输入的转换为IP地址
                IPHostEntry IPHost=Dns.Resolve(this.textBox1.Text);
                
string teststr=IPHost.HostName;
                IPAddress[] addr
=IPHost.AddressList;
                
for(int i=0;i<addr.Length;i++)
                {
                    IpStr
+=addr[i];
                }
            }
            
catch(Exception er)
            {
                MessageBox.Show(er.Message);
            }
            
//IP地址字符串转换为IPAddress格式;
            myIP=IPAddress.Parse (IpStr);
            
try
            {
                Thread thread
=new Thread (new ThreadStart (accp)); //生成监听线程;
                thread.Start ();
            }
            
catch(Exception ee)
            {
                listBox1.Items.Add (ee.Message) ;
            }

        }
        
        
private void accp()
        {
            MyServer
=new IPEndPoint (myIP,Int32.Parse (textBox2.Text));//组合将访问主机的IP地址和端口号。
            sock=new Socket (AddressFamily.InterNetwork ,SocketType.Stream ,ProtocolType.Tcp );//实例化Socket对象。
            sock.Bind(MyServer);//绑定将访问的主机。
            sock.Listen (50);//开始监听,最大包长50。
            listBox1.Items.Add ("主机"+textBox1.Text +"端口"+textBox2.Text +"开始监听...... ");
            
while(true)
            {
                accsock
=sock.Accept ();//接收客户端的服务请求。
                if(accsock.Connected)
                {
                    listBox1.Items.Add (
"与客户建立连接。");
                    Thread thread
=new Thread (new ThreadStart (round));//如果有客户请求,生成与客户通信的线程。
                    thread.Start ();
                }
            }
        }

        
private void round()
        {
            
while(true)
            {
                Byte[] Rec
=new byte [64];
                NetworkStream netstream
=new NetworkStream (accsock);
                netstream.Read (Rec,
0,Rec.Length );//读取客户发送来的信息。
                string RecMessage=System.Text .Encoding .BigEndianUnicode .GetString (Rec);
                richTextBox1.AppendText (RecMessage
+" ");//写入到接收信息栏中。
            }
        }

        
private void button2_Click(object sender, System.EventArgs e)
        {
            
try
            {
                Byte[] sendbyte
=new Byte [64];
                
string send=richTextBox2.Text +" ";
                NetworkStream netstream
=new NetworkStream (accsock);//生成NetworkStream实例,用于发送基础数据流。
                sendbyte=System.Text .Encoding .BigEndianUnicode .GetBytes (send.ToCharArray ());
                netstream.Write (sendbyte,
0,sendbyte.Length );//向客户发送信息。
            }
            
catch
            {
                MessageBox.Show (
"连接没有建立!无法发送!");
            }

        }

        
private void button3_Click(object sender, System.EventArgs e)
        {
            
try
            {
                sock.Close ();
//停止监听服务。
                listBox1.Items .Add ("主机"+textBox1.Text +"端口"+textBox2.Text +"停止监听。 ");
            }
            
catch
            {
                MessageBox.Show (
"监听没有建立!关闭无效!");
            }
        }

    

        

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值