聊天例子

首先我们先设计好一个界面,如下图:

代码如下:
#region//声名变量
IPAddress HostIP = IPAddress.Parse(“127.0.0.1”);
IPEndPoint point;
Socket socket;
bool flag = true;
#endregion

   #region//声名委托
    delegate void SetTextCallback(string text);
    private void SetText(string text)
    {
       textBox2.AppendText(text + "\r\n");
   }
    #endregion

   #region//进程
   private void Proccess()
    {
        if (socket.Connected)
        {
            while (flag)
            {
                byte[] receiveByte = new byte[64];
                socket.Receive(receiveByte, receiveByte.Length, 0);
                string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);
                this.Invoke(new SetTextCallback(SetText),new object[]{strInfo});  
            }
        }
    }
   #endregion
    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            Byte[] sendByte = new Byte[64];
            string sendStr = this.textBox1.Text + ":" + this.textBox3.Text+"\r\n";
            sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
            socket.Send(sendByte, sendByte.Length, 0);


        }
        catch { }
    }
    
    public Form1()
        {
            InitializeComponent();
        }

           private void button1_Click(object sender, EventArgs e)
        {
            HostIP = IPAddress.Parse(textBox1.Text.Trim());
            try
            {
                point = new IPEndPoint(HostIP, Int32.Parse("11000"));
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(point);

                Thread thread = new Thread(new ThreadStart(Proccess));
                thread.Start();
            }
            catch(Exception ey)
            {
                MessageBox.Show("服务器没有开启\r\n"+ey.Message);
            }
        }

    private void button3_Click(object sender, EventArgs e)
    {
        socket.Close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值