C# TCP通信(阉割版)

在这里插入图片描述
#客户端代码:

using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace WindowsClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }
        Socket socketClient = null;//创建socket套接字
        void ShowMessage(string str)//打印消息
        {
            show_Text.AppendText(str + "\r\n");
        }
        private void conn_button_Click(object sender, EventArgs e)
        {
            //1.创建套接字
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//ipv4、TCP
            //2.获取IP及连接ip&端口号
            ip_text.Text = "127.0.0.1";
            port_text.Text = "8080";
            IPAddress ip = IPAddress.Parse(ip_text.Text.Trim());
            IPEndPoint ip_port = new IPEndPoint(ip, int.Parse(port_text.Text.Trim()));
            try
            {
                ShowMessage("与服务器连接中...");
                socketClient.Connect(ip_port);
            }
            catch
            {
                MessageBox.Show("连接失败");
                return;
            }
            ShowMessage("与服务器连接成功!");
        }
        private void send_button_Click(object sender, EventArgs e)
        {
            string strMsg = " :" + send_Text.Text.Trim() + "\r\n";
            byte[] buff = System.Text.Encoding.UTF8.GetBytes(strMsg);
            socketClient.Send(buff); // 发送消息;
            ShowMessage("向服务器发送"+strMsg);
            send_Text.Clear();
        }
        private void Form1_Load(object sender, EventArgs e)
        { }
    }
}

#服务端

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;  // IP,IPAddress, IPEndPoint,端口等;
using System.Threading;
namespace WindowsServer
{
    public partial class From1 : Form
    {     
        public From1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();  
        }
        public static bool recvStatus = false;//确认接收
        Thread threadServer = null;//监听客户端连接请求的线程
        Socket socketServer = null;//创建socket套接字
        Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
        Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
        private void Listenbutton_Click(object sender, EventArgs e) //(激活)监听事件
        {
            //1.创建套接字
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//ipv4、TCP
            //2.获取IP及连接ip&端口号
            ip_text.Text = "127.0.0.1";
            port_text.Text = "8080";
            IPAddress ip = IPAddress.Parse(ip_text.Text.Trim());
            IPEndPoint ip_port = new IPEndPoint(ip, int.Parse(port_text.Text.Trim()));
            try
            {
                //3.绑定套接字与ip&port
                socketServer.Bind(ip_port);
            }
            catch
            {
                MessageBox.Show("绑定套接字失败");
                return;
            }
            //4.设置监听的数量
            socketServer.Listen(5);
            //5.****创建监听线程****
            threadServer = new Thread(WatchConnecting)
            {
                IsBackground = true//??
            };
            threadServer.Start();
            ShowMessage("监听服务启动成功!");
        }
        public void WatchConnecting()//监听线程
        {
            while (true)//持续监听
            {
                //5.1监听客户端连接请求,返回??客户端套接字
                Socket sock_conn_temp = socketServer.Accept();
                //5.2将客户端信息添加到dict集合中
                dict.Add(sock_conn_temp.RemoteEndPoint.ToString(), sock_conn_temp);
                //打印客户端信息
                ShowMessage("与客户端:" + sock_conn_temp.RemoteEndPoint.ToString() + "连接成功!!!");
                //5.3将当前监听线程添加的dictThread集合中
                Thread thr_temp = new Thread(RecvMessage)
                {
                    IsBackground = true
                };
                thr_temp.Start(sock_conn_temp);
                dictThread.Add(sock_conn_temp.RemoteEndPoint.ToString(), thr_temp);
            }
        }
        public void RecvMessage(object sokConnectionparn)//接收客户端信息;
        {
            Socket sock_client_temp = sokConnectionparn as Socket;//??
            if (!recvStatus)
            {
                ShowMessage("请先确认接收消息...");
            }
            while (true)
            {
                    //5.3.1存储客户端发送的数据
                    byte[] buff = new byte[1024 * 1024 * 2];//2M
                    int length = -1;
                    try
                    {
                        length = sock_client_temp.Receive(buff);
                    }
                    catch (SocketException se)
                    {
                        ShowMessage("发生套接字错误异常");
                        //5.3.2从dict集合中删除当前套接字
                        dict.Remove(sock_client_temp.RemoteEndPoint.ToString());
                        //5.3.3从dictThread集合中删除当前线程
                        dictThread.Remove(sock_client_temp.RemoteEndPoint.ToString());
                        ShowMessage("与客户端:" + sock_client_temp.RemoteEndPoint.ToString() + "中断连接!!!");
                        recvStatus = false;
                        break;
                    }
                    catch (Exception e)
                    {
                        ShowMessage("程序执行异常");
                        //5.3.2从dict集合中删除当前套接字
                        dict.Remove(sock_client_temp.RemoteEndPoint.ToString());
                        //5.3.3从dictThread集合中删除当前线程
                        dictThread.Remove(sock_client_temp.RemoteEndPoint.ToString());
                        ShowMessage("与客户端:" + sock_client_temp.RemoteEndPoint.ToString() + "中断连接!!!");
                        recvStatus = false;
                        break;
                    }
                  if (recvStatus)
                   {
                    string strMsg = "["+sock_client_temp.RemoteEndPoint.ToString() +"]"+ System.Text.Encoding.UTF8.GetString(buff, 1, length - 1);// 将接受到的字节数据转化成字符串;
                    ShowMessage(strMsg);
                    }         
            }
        }
       void ShowMessage(string str)//打印消息
        {
            show_Text.AppendText(str + "\r\n");
        }
       private void Recv_button_Click(object sender, EventArgs e)
        {
            ShowMessage("已确认");
            recvStatus =true;    
        }
        private void canc_button_Click(object sender, EventArgs e)
        {
            ShowMessage("已取消");
            recvStatus = false;
        }
        private void From1_Load(object sender, EventArgs e)
        {}
    }
}

在这里插入图片描述

转载源:http://www.cnblogs.com/zhangxiaoyong/p/6486311.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常好用的C#.net的TCP控件,this.vmTcpIpServer1.Collapse = false; this.vmTcpIpServer1.EnableLog = false; this.vmTcpIpServer1.IdleTime = -1; this.vmTcpIpServer1.LocalUsingIpAddr = "127.0.0.1"; this.vmTcpIpServer1.Location = new System.Drawing.Point(9, 17); this.vmTcpIpServer1.LogFilePath = "D:\\AppLog"; this.vmTcpIpServer1.MaxLogShownLines = 30; this.vmTcpIpServer1.Name = "vmTcpIpServer1"; this.vmTcpIpServer1.PackageHeader = UNYC.TcpIp.PackageHeader.None; this.vmTcpIpServer1.PackageTailer = UNYC.TcpIp.PackageTailer.None; this.vmTcpIpServer1.PortNum = 30000; this.vmTcpIpServer1.SaveToLogFile = false; this.vmTcpIpServer1.ShowTransContents = false; this.vmTcpIpServer1.Size = new System.Drawing.Size(266, 405); this.vmTcpIpServer1.TabIndex = 0; // // vmTcpIpClient1 // this.vmTcpIpClient1.AutoRecover = false; this.vmTcpIpClient1.Collapse = false; this.vmTcpIpClient1.ConnRetries = -1; this.vmTcpIpClient1.EnableLog = false; this.vmTcpIpClient1.IdleTime = -1; this.vmTcpIpClient1.IpAddr = "192.168.100.231"; this.vmTcpIpClient1.Location = new System.Drawing.Point(311, 17); this.vmTcpIpClient1.LogFilePath = "D:\\AppLog"; this.vmTcpIpClient1.MaxLogShownLines = 100; this.vmTcpIpClient1.Name = "vmTcpIpClient1"; this.vmTcpIpClient1.PackageHeader = UNYC.TcpIp.PackageHeader.None; this.vmTcpIpClient1.PackageTailer = UNYC.TcpIp.PackageTailer.None; this.vmTcpIpClient1.PingInterval = 500; this.vmTcpIpClient1.PortNum = 912815; this.vmTcpIpClient1.SaveToLogFile = false; this.vmTcpIpClient1.ShowTransContents = false; this.vmTcpIpClient1.Size = new System.Drawing.Size(266, 405);
.net 稳定 高效 易用 可同步 TCP 通信框架 使用平台: WinXP,WIN7,WIN8,WINCE,WINPHONE。 使用.net 2.0 框架。 主要功能介绍: 1、可以代替 Oracle,Mysql客户端 在不安装Oracle,MySql客户端的情况下访问, 对数据库进行间接访问(需开始框架的服务器端)。 2、可以使本来没有网经功能的Sqlite具有网络访问的能力。(也是需要开启服务器端) 以上两点可以兼容现有代码生成器时,客户端代码仅需要特别小的改动就可以。 3、基本功能。可以实现聊天,传文件,图片。 4、使用长连接,有断线自动连接功能,心跳包。 5、使用自定义数据包协议,自建Session机制加强数据连接安全。 6、框架稳定,支持高并发。 7、简单的事件处理机制。使用更加简单。 8、支持同步处理,使程序的开发更架简单,不需要另行回调处理。 下载地址: 使用方式: 首选需要 引用 DataUtils.v1.1.dll。DataUtils 内包含客户端与服务器端 处理类。 1、服务器端 代码示例。 设置服务器端默认端口 ,不设置端口会使用默认端口 TcpSettings.DefultPort = 8511; 既可以使用静态默认对象,也可以创建服务器端对象。 SocketListener server= new SocketListener(); 对象创建后 注册一些事件,以接收客户端发送的信息。 SocketListener.Server.RegeditSession += new Feng.Net.Tcp.SocketListener.RegeditSessionEventHandler(server_RegeditSession); RegeditSession 事件用于是否允许客户端连接此服务器。可以使用用户名,密码的核对方式。 SocketListener.Server.DataReceive += new SocketListener.DataReceiveEventHandler(server_DataReceive); DataReceive 在这个事件里处理接收到的数据。 事件注册完成就可以打开监听 SocketListener.Server.StartListening(); 2、客户端 代码示例 设置服务器的IP地址 TcpSettings.DeafultIPAddress = "192.168.1.3"; TcpSettings.DefultPort = 8511;//不设置端口会使用默认端口。 这样就可以使用默认的静态客户端了。 也可以自己创建对象。 客户端创建后需要在Connected事件注册用户,以限制某些用户是否可以使此链接。用户来源可以是数据库等。 void client_Connected(object sender, SocketClient sh) { Client.RegeditSession("aaa", "bbb"); } 发送文字消息给其他用户 SocketClient.Client.SendToOtherUser(string user, string text); //USER代表发达的目白用户,text表示为发送的内容。 发送图片,音频,视屏可以使用 SocketClient..SendToOtherUser(string user, byte[] data)////USER代表发达的目白用户,data表示为发送的内容。 data数据中数据有多种类型时可以使用 using (Feng.IO.BufferWriter bw = new Feng.IO.BufferWriter()) { bw.WriteBitmap(new Bitmap(100, 100)); bw.Write(text);

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值