C#Socket 案例

服务器端

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;
using System.IO;
namespace wangluoqi
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //点击监听按钮时 创建Socket对像
            Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket对象,如果用UDP协议,则要用SocketTyype.Dgram类型的套接字

            //声明ip地址
            IPAddress ip = IPAddress.Any;

            //创建端口对像
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtprot.Text));

            //开始监听
            socketWatch.Bind(point);
            ShowMsg("监听成功");
            //声明一秒内可同时连接的客户端
            socketWatch.Listen(10);

            //创建后台进程用来监听连接
            Thread td = new Thread(listen);
            td.IsBackground = true;
            td.Start(socketWatch);

        }
        Socket socketSend;
        Dictionary<string, Socket> dc = new Dictionary<string, Socket>();
        /// <summary>
        /// 创建通信的客户端
        /// </summary>
        /// <param name="o"></param>
        void listen(object o)
        {
            //把对像转成socket 如果不为socket 返回null
            Socket socketwatch = o as Socket;
            while (true)
            {     //等待客户端连接 创建一个负责通信的Socket
                socketSend = socketwatch.Accept();
                dc.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                comboBox1.Items.Add(socketSend.RemoteEndPoint.ToString());
                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":连接成功");

                //新建一个进程,以免程序假死
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start(socketSend);

            }
        }

        /// <summary>
        /// 不停的接收传过来的数据
        /// </summary>
        /// <param name="o"></param>
        void Receive(object o)
        {
            try
            {
                while (true)
                {
                    Socket socketSend = o as Socket;

                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketSend.RemoteEndPoint + ":" + str);
                }
            }
            catch { }
        }

        private void ShowMsg(string str)
        {
            txtlog.AppendText(str + "\r\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消跨线层访问判断
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string str = txtsend.Text;
            byte[] buf = Encoding.UTF8.GetBytes(str);
            List<byte> blist = new List<byte>();
            blist.Add(0);
            blist.AddRange(buf);
            //将泛型集合转为数组
            byte[] nbuf = blist.ToArray();

            if (comboBox1.SelectedItem == null)
            {
                comboBox1.SelectedIndex = 0;
            }
            dc[comboBox1.SelectedItem.ToString()].Send(nbuf);

        //  socketSend.Send(buf);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog odg = new OpenFileDialog();
            odg.InitialDirectory = @"C:\Users\Administrator\Desktop";
            odg.ShowDialog();

            string filepath = odg.FileName;
            txtfilename.Text = filepath;

        }

        //发送文本
        private void button3_Click(object sender, EventArgs e)
        {
            string stpath = txtfilename.Text;
            if (comboBox1.SelectedItem == null)
            {
                comboBox1.SelectedIndex = 0;
            }
            using(FileStream fsRead=new FileStream(stpath,FileMode.OpenOrCreate,FileAccess.Read))
            {
                byte[] buf = new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buf, 0, buf.Length);
                List<byte> nlist= new List<byte>();
                nlist.Add(1);
                nlist.AddRange(buf);
                //将集合转为数组;
                byte[] nbuf = nlist.ToArray();
                dc[comboBox1.SelectedItem.ToString()].Send(nbuf, 0, r+1, SocketFlags.None);
            }
        }

        //发送窗口抖动
        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == null)
            {
                comboBox1.SelectedIndex = 0;
            }
            byte[] buf = new byte[1];
            buf[0] = 2;
            dc[comboBox1.SelectedItem.ToString()].Send(buf);
        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
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 clent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //连接服务器
        private void button1_Click(object sender, EventArgs e)
        {
            //创建连接用的socket

            //创建连接点
            IPAddress ip = IPAddress.Parse(txtip.Text);
            //创建要连接的网络点
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtpint.Text));

            //连接
            socketsend.Connect(point);
            ShowMsg("连接成功");

            //创建一个后台线层,用于接收服务器发来的数据
            Thread td = new Thread(jssend);
            td.IsBackground = true;
            td.Start();

        }

        /// <summary>
        /// 接收数据
        /// </summary>
        void jssend()
        {
            try
                {
            while (true)
            {

                    byte[] buf = new byte[1024 * 1024 * 2];
                    //实际接收到的字符数
                    int r = socketsend.Receive(buf);
                    if (r == 0)
                    {
                        break;
                    }
                //表示接收到的数据是文本
                    if (buf[0] == 0)
                    {
                        string str = Encoding.UTF8.GetString(buf, 1, r-1);
                        txtlog.AppendText(socketsend.RemoteEndPoint + ":" + str + "\r\n");
                    }
                    else if (buf[0] == 1)//表示接收到的数据是文件
                    {
                        SaveFileDialog sdg = new SaveFileDialog();
                        sdg.InitialDirectory = @"C:\Users\Administrator\Desktop";
                        sdg.Title = "选择保存位置";
                        sdg.ShowDialog(this);//此处一定要添加this

                        string filename = sdg.FileName;
                        using (FileStream fsw = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            fsw.Write(buf, 1, r - 1);
                        }
                        MessageBox.Show("保存成功");

                    }
                    else if (buf[0] == 2)//表示接收到的数据是窗口抖动
                    {
                        int x = this.Location.X;
                        int y = this.Location.Y;
                        for (int i = 0; i < 100; i++)
                        {
                            this.Location = new Point(x - 10, y - 10);
                            this.Location = new Point(x, y);

                        }
                    }

                }
            }
            catch{}
        }

        void ShowMsg(string str)
        {
            txtlog.AppendText(str + "\r\n");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] buf = Encoding.UTF8.GetBytes(txtsend.Text);
            socketsend.Send(buf);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}

实例下载

时间: 2024-08-11 20:13:21

C#Socket 案例的相关文章

c# Socket案例 (部分代码解释)

IPAddress address = IPAddress.Parse(ipString); 上述代码解释为:将IP地址字符串转换为IPAddress实例 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 上述代码解释为:创建套接字,AddressFamily 枚举指定 Socket 类用其解析网络地址的标准地址系列(例如,AddressFamily.InterNetwork

lua socket案例

安装就不说了,上篇有写 location /chat/sub {    #ngx.header.content_type = "text/html";     default_type 'text/html';      content_by_lua_file /data/www/lua/sub.lua; } location /chat/pub {   default_type 'text/html';    content_by_lua_file /data/www/lua/pub

一个Android Socket的例子(转)

1.开篇简介 Socket本质上就是Java封装了传输层上的TCP协议(注:UDP用的是DatagramSocket类).要实现Socket的传输,需要构建客户端和服务器端.另外,传输的数据可以是字符串和字节.字符串传输主要用于简单的应用,比较复杂的应用(比如Java和C++进行通信),往往需要构建自己的应用层规则(类似于应用层协议),并用字节来传输. 2.基于字符串传输的Socket案例 1)服务器端代码(基于控制台的应用程序,模拟) import java.io.BufferedReader

一个Android Socket的例子

1.开篇简介 Socket本质上就是Java封装了传输层上的TCP协议(注:UDP用的是DatagramSocket类).要实现Socket的传输,需要构建客户端和服务器端.另外,传输的数据可以是字符串和字节.字符串传输主要用于简单的应用,比较复杂的应用(比如Java和C++进行通信),往往需要构建自己的应用层规则(类似于应用层协议),并用字节来传输. 2.基于字符串传输的Socket案例 1)服务器端代码(基于控制台的应用程序,模拟) import java.io.BufferedReader

python - socket通信笔记

参考: 通过编写聊天程序来熟悉python中多线程和socket的用法:https://www.cnblogs.com/mingjiatang/p/4905395.html python socket通信:https://yq.aliyun.com/articles/40745?spm=5176.100239.blogcont40768.17.FIFTZv 1.socket使用方法 a.在python中使用socket时要iamport socket b.在使用socket中又服务器端和客户端之

1高并发服务器:多路IO之select

 1 select A:select能监听的文件描述符个数受限于FD_SETSIZE,一般为1024,单纯改变进程打开 的文件描述符个数并不能改变select监听文件个数 B:解决1024以下客户端时使用select是很合适的,但如果链接客户端过多,select采用的是轮询模型,会大大降低服务器响应效率,不应在select上投入更多精力 2 依赖的头文件 #include <sys/select.h> /* According to earlier standards */ #includ

1高并发server:多路IO之select

?? 1 select A:select能监听的文件描写叙述符个数受限于FD_SETSIZE,一般为1024.单纯改变进程打开 的文件描写叙述符个数并不能改变select监听文件个数 B:解决1024下面client时使用select是非常合适的,但假设链接client过多,select採用的是轮询模型,会大大减少server响应效率.不应在select上投入很多其它精力 2 依赖的头文件 #include <sys/select.h> /* According to earlier stan

UDP(socket)接和数据案例封装成C++代码

 配置QT下的pro文件 TEMPLATE = app CONFIG += console CONFIG -= app_bundle CONFIG -= qt   LIBS += -lWs2_32   ##标示使用window下的Ws2_32.lib,-l表示要链接后面的库 #-lWs2_32,link Ws2_32.lib   SOURCES += main.cpp \     udp.cpp   HEADERS += \     udp.h 编写udp.h文件 #ifndef UDP_H

Window下UDP(socket)接和收数据案例

 配置QT的环境变量,这台电脑à属性à高级系统设置à高级à环境变量à系统变量àpathàC:\Qt\Qt5.3.0\5.3\mingw482_32\bin;C:\Qt\Qt5.3.0\Tools\QtCreator\bin 创建一个QT项目:winAndLinuxMyUdpProject项目 修改QT的项目文件,修改winAndLinuxMyUdpProject.pro文件: 注意,这的的:LIBS+= -lWs2_32  ##标示使用window下的Ws2_32.lib,-l表示要链接后面