知识基础:
1.按网络覆盖范围,计算机网络可分类为广域网、城域网、局域网和Internet。
2.在TCP/IP网络中测试连通性的常用命令是Ping 命令,ipconfig。
3.Internet的核心协议是TCP/IP 。
4.IP地址127.0.0.1是一个测试地址。
5.Internet的前身是Arpanet 。
6.在企业内部网与外部网之间,用来检查网络请求分组是否合法,保护网络资源不被非法使用的技术是防火墙技术。
7.设置防火墙的主要目的是防止局域网外部的非法访问。
8.防火墙:防火墙(Firewall),也称防护墙,它是一种位于内部网络与外部网络之间的网络安全系统。一项信息安全的防护系统,依照特定的规则,允许或是限制传输的数据通过。
socket通信
①:创建一个用于监听连接的Socket对象;
②:用指定的端口号和服务器的Ip建立一个EndPoint对象;
③:用Socket对象的Bind()方法绑定EndPoint;
④:用Socket对象的Listen()方法开始监听;
⑤:接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
⑥:通信结束后一定记得关闭Socket。
服务端窗口设计:
在这里插入图片描述
服务端源码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace _04socket通信服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //在多线程编程中,如果子线程需要使用主线程中创建的对象
            CheckForIllegalCrossThreadCalls = false;
        }
        Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();

        private void label1_Click(object sender, EventArgs e)
        {
            //127.0.0.1一般可视作本地IP
            string ip = IPAddress.Any.ToString();
            textBox1.Text = ip;
        }
        private void Setserver()
        {
            //1.创建服务器端电话
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //2.创建手机卡
            IPAddress iP = IPAddress.Parse(textBox1.Text);
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));
            //3.将电话卡插入到电话中
            server.Bind(endPoint);
            //4.开始监听电话
            //同一时刻允许同时加入链接的最大数量
            server.Listen(20);
            listBox1.Items.Add("服务器已经成功开启!");
            //5.等待来电接电话
            while (true)
            {
                //接受接入的一个客户端
                connectClient = server.Accept();
                if (connectClient != null)
                {
                    string info = connectClient.RemoteEndPoint.ToString();
                    clientList.Add(info, connectClient);
                    listBox1.Items.Add(info + "加入服务器!");
                    string msg = DateTime.Now + "你已经成功进入聊天室!";
                    SendMsg(msg);
                    //每有一个客户端接入,需要有一个线程进行服务
                    Thread threadclient = new Thread(ReciveMsg);
                    threadclient.IsBackground = true;
                    //设置这个线程中的通信对象时对应的socket与客户端socket进行通信
                    threadclient.Start(connectClient);
                }
            }
        }
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    byte[] arrMsg = new byte[1024 * 1024];
                    int length = client.Receive(arrMsg);
                    if (length > 0)
                    {
                        string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
                        IPEndPoint endPoint = client.RemoteEndPoint as IPEndPoint;
                        listBox1.Items.Add(DateTime.Now + "[" + endPoint.Port.ToString() + "]" + recMsg);
                        SendMsg("[" + endPoint.Port.ToString() + "]" + recMsg);
                    }
                }
                catch (Exception)
                {
                    client.Close();
                    clientList.Remove(client.RemoteEndPoint.ToString());
                }
            }
        }
        Socket connectClient;
        void SendMsg(string str)
        {
            foreach (var item in clientList)
            {
                byte[] arrMsg = Encoding.UTF8.GetBytes(str);
                item.Value.Send(arrMsg);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(Setserver);
            thread.IsBackground = true;
            thread.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != null)
            {

                SendMsg(DateTime.Now+textBox3.Text);
                textBox3.Text = "";
            }
        }
    }
}

客户端窗口设计:
在这里插入图片描述
客户端源码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace _01socket客户端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        Socket client;

        private void button1_Click(object sender, EventArgs e)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            IPAddress ip = IPAddress.Parse(textBox1.Text);
            IPEndPoint endpoint = new IPEndPoint(ip, int.Parse(textBox2.Text));

            client.Connect(endpoint);

            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
        }
        /// <summary>
        /// 接受数据
        /// </summary>
        /// <param name="o"></param>
        void ReciveMsg(object o)
        {
            client = o as Socket;
            while (true)
            {
                byte[] arrlist = new byte[1024 * 1024];
                int length = client.Receive(arrlist);
                string msg = DateTime.Now + Encoding.UTF8.GetString(arrlist, 0, length);
                listBox1.Items.Add(msg);
            }
        }

        void SendMsg(string msg)
        {
            byte[] arrmsg = Encoding.UTF8.GetBytes(msg);
            client.Send(arrmsg);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                SendMsg(textBox3.Text);
                textBox3.Text = "";
            }
        }
    }
}

执行效果:
在这里插入图片描述

posted on 2019-02-15 17:28  豆皮没有豆  阅读(475)  评论(0)    收藏  举报