c#实现简单的即时通讯(2)----客户端

来源:互联网 发布:windows找不到文件c 编辑:程序博客网 时间:2024/05/17 02:56

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace MyClient{    public partial class From1 : Form    {        public From1()        {            InitializeComponent();            TextBox.CheckForIllegalCrossThreadCalls = false;        }        Socket socketClient = null;        Thread threadClient = null;        private void ButtonConnect_Click(object sender, EventArgs e)        {            socketClient = new Socket(AddressFamily.InterNetwork,                SocketType.Stream,                ProtocolType.Tcp);            IPAddress ipaddress = IPAddress.Parse(TextBoxIP.Text.Trim());            IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(TextBoxPort.Text.Trim()));            socketClient.Connect(endpoint);            threadClient = new Thread(RecMsg);            threadClient.IsBackground = true;            threadClient.Start();        }        private void RecMsg()        {            while (true)            {                byte[] arrRecMsg = new byte[1024 * 1024];                int length = socketClient.Receive(arrRecMsg);                string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, 0, length);                TextBoxRecord.AppendText(DateTime.Now.ToString() + "\r\n" + strRecMsg + "\r\n");            }        }        private void ClientSendMsg(string sendMsg)        {            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);            socketClient.Send(arrClientSendMsg);            TextBoxRecord.AppendText(DateTime.Now.ToString() + "\r\n" + sendMsg + "\r\n");        }        private void ButtonSendMessage_Click(object sender, EventArgs e)        {            ClientSendMsg(TextBoxMessage.Text.Trim());        }        private void TextBoxMessage_KeyDown(object sender, KeyEventArgs e)        {            if (e.KeyCode == Keys.Enter)            {                ClientSendMsg(TextBoxMessage.Text.Trim());            }        }    }}


原创粉丝点击