peer to peer(点对点)实例(多线程)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace servers
{
    class mySocket
    {
        /// <summary>
        /// 启动监听:监听客户机请求
        /// </summary>
        public void myStartUp()
        {
            IPAddress s_ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
            s_ip = IPAddress.Parse("192.168.1.128");
            TcpListener m_listen = new TcpListener(s_ip, 8888);
            m_listen.Start();//启动监听
            //public delegate void myThread()
            int t = 1;
            Console.WriteLine("已经启监听程序,正在监听中...!");
            while (true)
            {
                ///接受到client连接,为此连接建立新的socket,并接受信息
                Socket c_pc = m_listen.AcceptSocket(); //接受客户端的连接(建立连接)
                Console.WriteLine("已经与新用户建立连接!");
                
                byte[] bytes = new byte[1024];
                c_pc.Receive(bytes);//从 System.Net.Sockets.NetworkStream 读取数据

                string dataContent = Encoding.Unicode.GetString(bytes, 0, bytes.Length);//将指定字节数组中的一个字节序列解码为一个字符串。

                Console.WriteLine("--" + dataContent.TrimEnd('\0'));//将输出到控制台。将指定的字符串值(后跟当前行终止符)写入标准输出流。

                bytes = Encoding.Unicode.GetBytes(dataContent.ToUpper());//将字符串转换成大写字母后,再将字符编码为一个字节序列。
                c_pc.Send(bytes);//将数据写入流。(将数据写入 System.Net.Sockets.NetworkStream)

                Thread clientServerThread = new Thread(new ParameterizedThreadStart(myThreadFunc));
                clientServerThread.Start(c_pc);
            }


        }


        public void myThreadFunc(object obj)
        {
            Socket stream = obj as Socket;
            while (true)
            {
                
                try
                {
                    bool t = stream.Poll(10, SelectMode.SelectWrite);
                    byte[] clients = new byte[1024];
                    stream.Receive(clients);
                    stream.Send(clients);//当客户端的网络或主机意外关闭时,用此方法去验证,触发一个错误来中断当前线程和服务。(客户端意外终止时仍然可以读取流信息,只是为空而已)


                    string clientData = Encoding.Unicode.GetString(clients, 0, clients.Length);
                    Console.WriteLine(clientData.TrimEnd('\0'));
                }
                catch (Exception)
                {
                    Console.WriteLine("关闭" + Thread.CurrentThread.Name);
                    Thread.CurrentThread.Abort();
                    stream.Close();
                }

                Thread.Sleep(1000);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值