网络编程

IP地址和端口号用来识别网络程序。

特殊Ip 127.0.0.1 本地网卡测试用


服务器

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace C03聊天室服务端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }

        //服务端 监听套接字
        Socket sokWatch = null;
        //服务端 监听线程
        Thread thrWatch = null;
        //字典集合:保存 通信套接字
        Dictionary<string, Socket> dictCon = new Dictionary<string, Socket>();

        private void btnStartListen_Click(object sender, EventArgs e)
        {
            //1.创建监听套接字 使用 ip4协议,流式传输,TCP连接
            sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2.绑定端口
            //2.1获取网络节点对象
            IPAddress address = IPAddress.Parse(txtIP.Text);
            IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text));
            //2.2绑定端口(其实内部 就向系统的 端口表中 注册 了一个端口,并指定了当前程序句柄)
            sokWatch.Bind(endPoint);
            //2.3设置监听队列
            sokWatch.Listen(10);
            //2.4开始监听,调用监听线程 执行 监听套接字的 监听方法
            thrWatch = new Thread(WatchConnecting);
            thrWatch.IsBackground = true;
            thrWatch.Start();
            ShowMsg("服务器启动啦~~!");
        }

        #region 1.0 服务端监听方法 void WatchConnecting()
        /// <summary>
        /// 服务端监听方法
        /// </summary>
        void WatchConnecting()
        {
            //2.4开始监听:此方法会阻断当前线程,直到有 其它程序 连接过来,才执行完毕
            Socket sokMsg = sokWatch.Accept();
            //将当前连接成功的 【与客户端通信的套接字】 的 标识 保存起来,并显示到 列表中
            //将 远程客户端的 ip和端口 字符串 存入 列表
            lbOnline.Items.Add(sokMsg.RemoteEndPoint.ToString());
            //将 服务端的通信套接字 存入 字典集合
            dictCon.Add(sokMsg.RemoteEndPoint.ToString(), sokMsg);

            ShowMsg("有客户端连接了~~!");
            //2.5创建 通信线程
            Thread thrMsg = new Thread(ReceiveMsg);
            thrMsg.IsBackground = true;
            thrMsg.Start(sokMsg);
        } 
        #endregion

        #region 2.0 接收客户端消息
        bool isReceive = true;
        void ReceiveMsg(object obj)
        {
            Socket sokMsg = obj as Socket;
            //3.通信套接字 监听 客户端的 消息
            //3.1创建 消息缓存区
            byte[] arrMsg = new byte[1024 * 1024 * 1];
            while (isReceive)
            {
                //3.2接收客户端的消息 并存入 缓存区,注意:Receive方法也会阻断当前的线程
                sokMsg.Receive(arrMsg);
                //3.3将接收到的消息 转成 字符串
                string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg);
                //3.4将消息 显示到 文本框
                ShowMsg(strMsg);
            }
        } 
        #endregion

        void ShowMsg(string strmsg)
        {
            this.txtShow.AppendText(strmsg + "\r\n");
        }

        /// <summary>
        /// 3.0 服务端 向指定 的客户端 发送 消息
        /// </summary>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string strClient = lbOnline.Text;
            if(dictCon.ContainsKey(strClient)){
                string strMsg = txtInput.Text.Trim();
                ShowMsg("向客户端【" + strClient + "】说:" + strMsg);

                //使用 指定的 通信套接字 将 字符串 发送到 指定的客户端
                byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
                dictCon[strClient].Send(arrMsg);
            }
        }

        /// <summary>
        /// 3.0
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendFile_Click(object sender, EventArgs e)
        {

        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace C04聊天室客户端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }
        //客户端 通信套接字
        Socket sokMsg = null;
        //客户端 通信线程
        Thread thrMsg = null;


        private void btnConnect_Click(object sender, EventArgs e)
        {
            //1.创建监听套接字 使用 ip4协议,流式传输,TCP连接
            sokMsg = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2.获取要连接的服务端 节点
            //2.1获取网络节点对象
            IPAddress address = IPAddress.Parse(txtIP.Text);
            IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text));
            //3.向服务端 发送链接请求
            sokMsg.Connect(endPoint);
            ShowMsg("连接服务器成功~~!");
            //4.开启通信线程
            thrMsg = new Thread(RecevieMsg);
            thrMsg.IsBackground = true;
            thrMsg.Start();
        }

        bool isRec = true;
        void RecevieMsg()
        {
            //3.1创建 消息缓存区
            byte[] arrMsg = new byte[1024 * 1024 * 1];
            while (isRec)
            {
                sokMsg.Receive(arrMsg);
                string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg);
                ShowMsg("服务器说:" + strMsg);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string strMsg = txtInput.Text.Trim();
            byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
            sokMsg.Send(arrMsg);
        }


        void ShowMsg(string strmsg)
        {
            this.txtShow.AppendText(strmsg + "\r\n");
        }
    }
}

实现了基本的客户端和服务器端的通信



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值