日期:2014-05-17  浏览次数:21234 次

Socket 编程,一个服务器,多个客户端,互相通信(分享)
今天我看帖子,有很多关于问Socket的问题.

但是我只能给大家一个很简单的Socket的初级通信.

给大家做一个小的服务器,刚刚好前段时间做了一个小的聊天程序,实现了:

指定客户端发送消息,发送闪屏,支持服务器监听客户端发送消息

具体的代码如下:

首先是服务器.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;//Endpoint
using System.Net.Sockets;//包含套接字
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;//关闭跨线程修改控件检查
        }


        Socket sokWatch = null;//负责监听 客户端段 连接请求的  套接字(女生宿舍的大妈)
        Thread threadWatch = null;//负责 调用套接字, 执行 监听请求的线程

        //开启监听 按钮
        private void btnStartListen_Click(object sender, EventArgs e)
        {
            //实例化 套接字 (ip4寻址协议,流式传输,TCP协议)
            sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建 ip对象
            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
            //创建网络节点对象 包含 ip和port
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
            //将 监听套接字  绑定到 对应的IP和端口
            sokWatch.Bind(endpoint);
            //设置 监听队列 长度为10(同时能够处理 10个连接请求)
            sokWatch.Listen(10);
            threadWatch = new Thread(StartWatch);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            txtShow.AppendText("启动服务器成功......\r\n");
        }

        //Dictionary<string, Socket> dictSocket = new Dictionary<string, Socket>();
        Dictionary<string, ConnectionClient> dictConn = new Dictionary<string, ConnectionClien