C# Socket编程

Service

创建一个Windows窗体应用
在这里插入图片描述
在这里插入图片描述
属性值:
在这里插入图片描述
首先我们编写启动按钮(监听):

        IPAddress ip;
        TcpListener listener;
        private void buttonStart_Click(object sender, EventArgs e)
        {
            ip = IPAddress.Parse(this.textBoxIP.Text); //创建IP
            listener = new TcpListener(ip,Convert.ToInt32(this.textBoxPort.Text)); //创建TCP监听对象
            listener.Start();
            this.textBoxInfo.Text = "服务器启动-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
        
        }

在这里插入图片描述

Client

在这里插入图片描述
在这里插入图片描述
各属性名称:
在这里插入图片描述
双击连接(创建与服务器端的连接):

        TcpClient tcpClient;
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();
            try
            {
                tcpClient.Connect(this.textBoxIP.Text, Convert.ToInt32(this.textBoxPort.Text));
                this.textBoxInfo.Text = "连接成功-" + DateTime.Now "\r\n" + this.textBoxInfo.Text;
            }
            catch(Exception ex)
            {
                MessageBox.Show("连接失败-" + ex.Message);
            }
        }

在这里插入图片描述

通信

在这里插入图片描述
Client

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "发送“" + message + "”-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray,0,byteArray.Length); //发送字节数组

        }

Service

        IPAddress ip;
        TcpListener listener;
        TcpClient tcpClient;
        private void buttonStart_Click(object sender, EventArgs e)
        {
            ip = IPAddress.Parse(this.textBoxIP.Text); //创建IP
            listener = new TcpListener(ip,Convert.ToInt32(this.textBoxPort.Text)); //创建TCP监听对象
            listener.Start();
            this.textBoxInfo.Text = "服务器启动-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
            tcpClient = listener.AcceptTcpClient(); //中断 等待客户端的连接
            this.textBoxInfo.Text = "有一个客户端连接成功-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = new byte[1024];
            int length = stream.Read(byteArray, 0, 1024); //会把流里面的字节数组 放到byteArray里面
            //length其实就是客户端发送的字节数组长度
            string receiveMessage = Encoding.Unicode.GetString(byteArray,0,length); this.textBoxInfo.Text = "有一个客户端连接成功-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
            this.textBoxInfo.Text = "接到的信息:"+ receiveMessage + " -" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;

        }

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值