C#Socket聊天室(小白整理)

最近算是0基础学了socket的编程,发现很多不友好。。其实是自己不知道,啊哈哈。最开始建立C#的脚本时要建立窗体,而不是控制台程序。之后建议根据界面,自己来写。还有别忘了Server和client建立两个程序哦。

图片分别为服务端,客户端。

Server       

代码:(designer.cs,Server)

private void InitializeComponent()
        {
            this.listen_btn = new System.Windows.Forms.Button();
            this.send_btn = new System.Windows.Forms.Button();
            this.txtIP = new System.Windows.Forms.TextBox();
            this.txtPort = new System.Windows.Forms.TextBox();
            this.txtLog = new System.Windows.Forms.RichTextBox();
            this.txtMsg = new System.Windows.Forms.RichTextBox();
            this.cboIpPort = new System.Windows.Forms.ComboBox();
            this.SuspendLayout();
            // 
            // listen_btn
            // 
            this.listen_btn.Location = new System.Drawing.Point(282, 12);
            this.listen_btn.Name = "listen_btn";
            this.listen_btn.Size = new System.Drawing.Size(90, 21);
            this.listen_btn.TabIndex = 1;
            this.listen_btn.Text = "开始监听";
            this.listen_btn.UseCompatibleTextRendering = true;
            this.listen_btn.Click += new System.EventHandler(this.Listen_Click);
            // 
            // send_btn
            // 
            this.send_btn.Location = new System.Drawing.Point(305, 409);
            this.send_btn.Name = "cancel";
            this.send_btn.Size = new System.Drawing.Size(130, 29);
            this.send_btn.TabIndex = 2;
            this.send_btn.Text = "发送消息";
            this.send_btn.UseCompatibleTextRendering = true;
            this.send_btn.Click += new System.EventHandler(this.send_Click);
            // 
            // txtIP
            // 
            this.txtIP.Location = new System.Drawing.Point(12, 12);
            this.txtIP.Name = "txtIP";
            this.txtIP.Size = new System.Drawing.Size(100, 21);
            this.txtIP.TabIndex = 1;
            this.txtIP.Text = "127.0.0.1";
            // 
            // txtPort
            // 
            this.txtPort.Location = new System.Drawing.Point(138, 12);
            this.txtPort.Name = "txtPort";
            this.txtPort.Size = new System.Drawing.Size(80, 21);
            this.txtPort.TabIndex = 1;
            // 
            // txtLog
            // 
            this.txtLog.Location = new System.Drawing.Point(12, 57);
            this.txtLog.Name = "txtLog";
            this.txtLog.Size = new System.Drawing.Size(423, 154);
            this.txtLog.TabIndex = 1;
            this.txtLog.Text = "";
            // 
            // txtMsg
            // 
            this.txtMsg.Location = new System.Drawing.Point(12, 230);
            this.txtMsg.Name = "txtMsg";
            this.txtMsg.Size = new System.Drawing.Size(423, 154);
            this.txtMsg.TabIndex = 3;
            this.txtMsg.Text = "";
            // 
            // cboIpPort
            // 
            this.cboIpPort.Location = new System.Drawing.Point(403, 9);
            this.cboIpPort.Name = "cboIpPort";
            this.cboIpPort.Size = new System.Drawing.Size(104, 24);
            this.cboIpPort.TabIndex = 4;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.Control;
            this.ClientSize = new System.Drawing.Size(834, 450);
            this.Controls.Add(this.txtMsg);
            this.Controls.Add(this.listen_btn);
            this.Controls.Add(this.txtIP);
            this.Controls.Add(this.send_btn);
            this.Controls.Add(this.txtPort);
            this.Controls.Add(this.txtLog);
            this.Controls.Add(this.cboIpPort);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        private System.Windows.Forms.Button listen_btn;
        private System.Windows.Forms.Button send_btn;
        private System.Windows.Forms.TextBox txtIP;
        private System.Windows.Forms.TextBox txtPort;
        private System.Windows.Forms.RichTextBox txtLog;

        private System.Windows.Forms.ComboBox cboIpPort;
        private System.Windows.Forms.RichTextBox txtMsg;
        #endregion
       
    }

正式的socket服务端代码

public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void Listen_Click(object sender, EventArgs e)
        {
            //ip地址
            IPAddress ip = IPAddress.Parse(txtIP.Text);
            //端口号
            IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Bind(point); //监听哪个端口号
                socket.Listen(10); //最大连接数
                ShowMsg("服务器开始监听");
                Thread thread = new Thread(AcceptInfo);
                thread.IsBackground = true;
                thread.Start(socket);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
        void AcceptInfo(object o)
        {
            Socket socket = o as Socket;
            while (true)
            {
                try
                {
                    Socket tSocket = socket.Accept();
                    string point = tSocket.RemoteEndPoint.ToString();
                    ShowMsg(point + "连接成功!");
                    cboIpPort.Items.Add(point);
                    dic.Add(point, tSocket);
                    Thread th = new Thread(ReceiveMsg);
                    th.IsBackground = true;
                    th.Start(tSocket);
                }
                catch (Exception ex)
                {
                    ShowMsg(ex.Message);
                    break;
                }
            }
        }
        void ReceiveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024];//接受数据
                    int n = client.Receive(buffer);//将接收到的数据放到buffer里,并返回实际长度
                    string words = Encoding.UTF8.GetString(buffer, 0, n);
                    ShowMsg(client.RemoteEndPoint.ToString() + ":" + words);
                }
                catch (Exception ex)
                {
                    ShowMsg(ex.Message);
                    break;
                }
            }
        }
        void ShowMsg(string msg)
        {
 
            txtLog.AppendText(msg+"\r\n");
 
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        private void send_Click(object sender, EventArgs e)
        {
            try
            {
                ShowMsg(txtMsg.Text);
                string ip = cboIpPort.Text; ;
                byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
                dic[ip].Send(buffer);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

   }

客户端Client代码(designer.cs部分的代码自行解决)

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false; //这句话如果没有会报出 “线程间操作无效: 从不是创建控件“的错误
        }
        Socket client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        private void conn_btn_Click(object sender, EventArgs e)
        {
            //连接到目标ip
            IPAddress ip = IPAddress.Parse(txtIP.Text);
            IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));
            try
            {
                client.Connect(point);
                ShowMsg("连接成功");
                ShowMsg("服务器" + client.RemoteEndPoint.ToString());
                ShowMsg("客户端" + client.LocalEndPoint.ToString());
                Thread th = new Thread(ReceiveMsg);
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception ex)
            {

                ShowMsg(ex.Message);
            }
        }
        void ReceiveMsg()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024];//接受数据
                    int n = client.Receive(buffer);//将接收到的数据放到buffer里,并返回实际长度
                    string words = Encoding.UTF8.GetString(buffer, 0, n);
                    ShowMsg(client.RemoteEndPoint.ToString() + ":" + words);
                }
                catch (Exception ex)
                {
                    ShowMsg(ex.Message);
                    break;
                }
            }
        }
        void ShowMsg(string msg)
        {

            txtInfo.AppendText(msg+"\r\n");

        }

        private void send_btn_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                try
                {
                    ShowMsg(txtMsg.Text);
                    byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
                    client.Send(buffer);
                }
                catch (Exception ex)
                {
                    ShowMsg(ex.Message);
                }
            }
        }
        private void ClientForm_Load(object sender, EventArgs e)

        {
           Control.CheckForIllegalCrossThreadCalls = false;
        }
}

socket代码参考http://www.cnblogs.com/weilengdeyu/archive/2013/03/08/2949101.html  微冷的雨出品---YYM

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值