zoukankan      html  css  js  c++  java
  • 利用P2P技术实现点对点聊天

    using System.Data;
    using System.IO;
    using System.Net.Sockets;
    using System.Threading;

    private Thread th;
    private TcpListener tcpl;
    private bool listenerRun = true;

    private void Listen()
    {
        
    try
        {
            tcpl 
    = new TcpListener(5656);
            tcpl.Start();
            statusBar1.Text 
    = "正在监听...";

            
    while(listenerRun)
            {
                Socket s 
    = tcpl.AcceptSocket();
                Byte[] stream 
    = new Byte[80];
                
    int i=s.Receive(stream) ;
                
    string message = System.Text.Encoding.UTF8.GetString(stream);
                richTextBox1.AppendText(message);
            }
        }
        
    catch(System.Security.SecurityException)
        {
            MessageBox.Show(
    "防火墙安全错误!""错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        
    catch(Exception)
        {
            statusBar1.Text 
    = "已停止监听!";
        }
    }

    private void Send()
    {
        
    try
        {
            
    string msg = "<"+textBox3.Text+">"+textBox2.Text;
            TcpClient tcpc 
    = new TcpClient(textBox1.Text, 5656);
            NetworkStream tcpStream 
    = tcpc.GetStream();

            StreamWriter reqStreamW 
    = new StreamWriter(tcpStream);
            reqStreamW.Write(msg);
            reqStreamW.Flush();
            tcpStream.Close();
            tcpc.Close();
            richTextBox1.AppendText(msg);
            textBox2.Clear();
        }
        
    catch(Exception)
        {
            statusBar1.Text 
    = "目标计算机拒绝连接请求!";
        }
    }

    private void Stop()
    {
        tcpl.Stop();
        th.Abort();
    }

    [STAThread]
    static void Main() 
    {
        Application.Run(
    new Form1());
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        button1.Enabled 
    = false;
        button2.Enabled 
    = true;
        th 
    = new Thread(new ThreadStart(Listen));    
        th.Start();
    }

    private void button2_Click(object sender, System.EventArgs e)
    {
        button1.Enabled 
    = true;
        button2.Enabled 
    = false;
        listenerRun 
    = false;
        Stop();
    }

    private void button3_Click(object sender, System.EventArgs e)
    {
        Send();
    }
  • 相关阅读:
    关于sencha touch中给文本添加焦点无效的解决方案
    sencha touch 入门系列 (五)sencha touch运行及代码解析(上)
    关于用phonegap 3.0+ 打包后sencha touch按钮点击切换动画延迟接近一秒的以及界面闪烁的解决方案
    Building a Simple User Interface(创建一个简单的用户界面)
    Running Your App(运行你的应用程序)
    android GridLayout布局
    Android Studio SVN的使用
    Android Library项目发布到JCenter最简单的配置方法
    AndroidStudio项目提交(更新)到github最详细步骤
    Android RecyclerView的使用
  • 原文地址:https://www.cnblogs.com/top5/p/1699474.html
Copyright © 2011-2022 走看看