.Net socket实现简单的聊天

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 SocketServer {
    public partial class Chat : Form {
        public Chat() {
            InitializeComponent();

            this.localip.Text = GetServerIP().ToString();
        }
        Thread mythread;
        Socket socket;

        public static IPAddress GetServerIP() {
            try {
                IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
                return ieh.AddressList[0];
            }
            catch {
                throw;
            }
        }

        public delegate void ShowResult(string msg);

        public void Show(string msg) {
            this.txtName.Text = msg.ToString();
        }
        public void ShowContents(string msg) {
            this.txtContents.Text += " /r/n "+msg;
        }
        public void Show2(string msg) {
            this.label1.Text = "ERR:"+msg.ToString();
        }

        private void BeginListen() {
            IPAddress ServerIP = GetServerIP();
            IPEndPoint iep = new IPEndPoint(ServerIP , Convert.ToInt32(this.localPort.Text));
            socket = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp);

            byte[] byteMessage = new byte[1024];
            //this.BeginInvoke(new ShowResult(Show) , new object[] { iep.ToString() });

            socket.Bind(iep);//绑定

            while (true) {
                try {
                    socket.Listen(10);

                    Socket newSocket = socket.Accept();

                    string sTime = DateTime.Now.ToShortDateString();
                    //string msg = sTime + ":" + "Message From:";
                    int len = newSocket.Receive(byteMessage);//获取接收字符长度
                    string strRec = System.Text.Encoding.Default.GetString(byteMessage , 0 , len);
                  //  msg += newSocket.RemoteEndPoint.ToString();// + Encoding.Default.GetString(byteMessage);

                    byte[] temp= new byte[1024];
                    Array.Copy(byteMessage , 0 , temp , 0,temp.Length);//根据temp的容量来取
                    string str = Encoding.Default.GetString(temp , 0 , temp.Length);

                    this.BeginInvoke(new ShowResult(ShowContents), new object[] { str });

                }
                catch (SocketException ex) {
                    this.BeginInvoke(new ShowResult(Show2) , new object[] { ex.ToString() });
                }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.localPort.Text.Trim().Equals(string.Empty)) {
                MessageBox.Show("localPort 不能为空");
                return;
            }
            try
            {
                mythread = new Thread(new ThreadStart(BeginListen));
                mythread.Start();
                this.button1.Enabled = false;
                this.button2.Enabled = true;
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
            }
        }

        private void button2_Click(object sender , EventArgs e) {
            if (mythread.ThreadState == ThreadState.Running) {
                mythread.Abort();
                //socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                this.button1.Enabled = true;
                this.button2.Enabled = false;

            }
        }

      
        IPAddress serverIP;
        int serverPort;
        Socket socketsend;

        private void button3_Click(object sender, EventArgs e) {
            string remotip =this.txtremotIP.Text.Trim();
            int remotPort = Convert.ToInt32(this.txtremotPort.Text.Trim());

            if (remotip.Equals(string.Empty) || remotPort.Equals(string.Empty)) {
                MessageBox.Show("远程IP与端口都不能为空");
                return;
            }
           int result = ConnectServer(remotip, remotPort);

           if (result.Equals(0)) {
               this.button3.Enabled = false;
           }

        }
        private int ConnectServer(string sIP, int sPort) {
            serverIP = IPAddress.Parse(sIP);
            serverPort = sPort;

            try {
                IPEndPoint iep = new IPEndPoint(serverIP, serverPort);

                socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socketsend.Connect(iep);

                return 0;
            } catch (Exception ex) {
                MessageBox.Show(ex.Message.ToString());
                return 1;
            }
        }

        private void btnSend_Click(object sender, EventArgs e) {
            if (socketsend != null && socketsend.Connected) {
                byte[] byteMessage;

                byteMessage = Encoding.Default.GetBytes(txtName.Text.Trim() + ":/r/n" + this.txtSendMsg.Text.Trim());

                socketsend.Send(byteMessage);
            }

        }

        private void Chat_FormClosing(object sender, FormClosingEventArgs e) {

            if (mythread != null && mythread.ThreadState == ThreadState.Running) {
                mythread.Abort();
                //socket.Shutdown(SocketShutdown.Both);
                socket.Close();

            }
            if (socketsend != null && socketsend.Connected) {
                socketsend.Shutdown(SocketShutdown.Both);
                socketsend.Close();
            }
        }

        private void button4_Click(object sender, EventArgs e) {
            BeginSend();
        }
        private void BeginSend() {

            try {
                string ip = this.txtremotIP.Text.Trim();
                string port = this.txtremotPort.Text.Trim();

                IPAddress serverIP = IPAddress.Parse(ip);
                int serverPort = Convert.ToInt32(port);

                IPEndPoint iep = new IPEndPoint(serverIP, serverPort);

                byte[] byteMessage;

                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socket.Connect(iep);
                string datestr = " "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string msg = txtName.Text.Trim()+ datestr +" :/r/n   " + this.txtSendMsg.Text.Trim();

                byteMessage = Encoding.Default.GetBytes(msg);

                socket.Send(byteMessage);

                socket.Shutdown(SocketShutdown.Both);

                socket.Close();

                ShowContents(msg);
            } catch { };
        }

        private void button5_Click(object sender, EventArgs e) {
            this.Close();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值