c# Socket通讯

实现局域网内部的机器之间通讯功能:

前段窗体的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace CHat
{
    public partial class Form1 : Form
    {
        private Thread th;
        private TcpListener tcpLis;
        private bool bLisRun = true;
        private NetworkStream ns;
        private StreamWriter sw;
        private TcpClient tcpCli;
        private Socket sk;
        public Form1()
        {
            InitializeComponent();
        }
        private void btnLink_Click(object sender, EventArgs e)
        {
            try
            {                
                tcpCli = new TcpClient(txtRemoteIP.Text, Convert.ToInt32(txtRemotePort.Text));//远程ip+port
                //向远程计算机提出连接申请             
                ns = tcpCli.GetStream();
                //如果连接申请建立,则获得用以传送数据的数据流 
                txtShowMsg.Text = "成功连接远程计算机!";
                btnDisLink.Enabled = true;
                btnLink.Enabled = false;
                btnSendMsg.Enabled = true;
            }
            catch (Exception)
            {
                txtShowMsg.Text = "目标计算机拒绝连接请求!";
            }
        }
        private void Listen()        
        {
            try
            {
                tcpLis = new TcpListener(Convert.ToInt32(txtLocalPort.Text));//端口
                tcpLis.Start(); //侦听指定端口号 

                txtShowMsg.Text = "正在监听...";
                //接受远程计算机的连接请求,并获得用以接收数据的Socket实例                         
                sk = tcpLis.AcceptSocket();
                //获得远程计算机对应的网络远程终结点
                EndPoint tempRemoteEP = sk.RemoteEndPoint;
                IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
                IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address);
                string HostName = host.HostName;
                //根据获得的远程计算机对应的网络远程终结点获得远程计算机的名称 
                txtShowMsg.Text = "'" + HostName + "' " + "远程计算机正确连接!";
                //循环侦听 
                while (bLisRun)//当点击disLink的时候,退出循环
                {
                    Byte[] stream = new Byte[80]; //定义从远程计算机接收到数据存放的数据缓冲区

                    string time = DateTime.Now.ToString(); //获得当前的时间 

                    int i = sk.ReceiveFrom(stream, ref tempRemoteEP); //接收数据,并存放到定义的缓冲区中 

                    string sMessage = System.Text.Encoding.UTF8.GetString(stream);//以指定的编码,从缓冲区中解析出内容 

                    listBox2.Items.Add(time + "" + HostName + ":");
                    listBox2.Items.Add(sMessage);
                    //显示接收到的数据            
                }
            }
            catch (System.Security.SecurityException)
            {
                MessageBox.Show("防火墙安全错误!", "错误",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }        
        }
        private void btnDisLink_Click(object sender, EventArgs e)
        {
            bLisRun = false;
            tcpCli.Close();
            txtShowMsg.Text = "断开连接!";
            btnLink.Enabled = true;
            btnSendMsg.Enabled = false;
        }
        private void btnListen_Click(object sender, EventArgs e)
        {
            th = new Thread(new ThreadStart(Listen));
            th.Start();
        }
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                string sMsg = txtSendMsg.Text;
                string MyName = Dns.GetHostName();
                //以特定的编码往向数据流中写入数据, 
                //默认为UTF8Encoding 的实例 
                sw = new StreamWriter(ns);
                //将字符串写入数据流中
                sw.Write(sMsg);
                //清理当前编写器的所有缓冲区,并使所有缓冲数据写入基础流 
                sw.Flush();           
                string time = DateTime.Now.ToString();
                //显示传送的数据和时间 
                listBox1.Items.Add(time + " " + MyName + ":");
                listBox1.Items.Add(sMsg);
                txtSendMsg.Clear();
            }
            //异常处理 
            catch (Exception)
            {
                txtShowMsg.Text = "无法发送信息到目标计算机!";
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }         
    }
}

主函数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CHat
{
    static class Program
    {
        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值