首页 > 其他分享 >socket 通讯练习 本机已通过

socket 通讯练习 本机已通过

时间:2023-03-16 12:33:08浏览次数:41  
标签:socket void 练习 System client new using 本机 ShowMsg


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;

namespace socketWF
{
public partial class FormS : Form
{
IPAddress ip;
IPEndPoint point;

    public FormS()
    {
        InitializeComponent();
        ServerListen();

    }
    private void ServerListen()
    {
        //ip地址 
        ip = IPAddress.Parse(txtIP.Text);
        // IPAddress ip = IPAddress.Any;
        //端口号
        point = new IPEndPoint(ip, int.Parse(txtPort.Text));
        //创建监听用的Socket 
        /*
        AddressFamily.InterNetWork:使用 IP4地址。
        SocketType.Stream:支持可靠、双向、基于连接的字节流,而不重复数据。此类型的 Socket 与单个对方主机进行通信,
        并且在通信开始之前需要远程主机连接。Stream 使用传输控制协议 (Tcp) ProtocolType 和 InterNetworkAddressFamily。 
        ProtocolType.Tcp:使用传输控制协议。  
        */
        //使用IPv4地址,流式socket方式,tcp协议传递数据  
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //创建好socket后,必须告诉socket绑定的IP地址和端口号。 
        //让socket监听point  
        try
        {
            //socket监听哪个端口 
            socket.Bind(point);
            //同一个时间点过来60个客户端,排队 
            socket.Listen(60);
            ShowMsg("服务器开始监听");
            Thread thread = new Thread(AcceptInfo);
            thread.IsBackground = true;
            thread.Start(socket);
        }
        catch (Exception ex)
        {
            ShowMsg(ex.Message);
        }
    }

    //记录通信用的Socket  
    Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
    // private Socket client; 
    void AcceptInfo(object o)
    {
        Socket socket = o as Socket;
        while (true)
        {
            //通信用socket 
            try
            {
                //创建通信用的Socket
                Socket tSocket = socket.Accept();
                string point = tSocket.RemoteEndPoint.ToString();
                //IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint;
                //string me = Dns.GetHostName();//得到本机名称
                //MessageBox.Show(me);
                ShowMsg(point + "连接成功!");
                ComboBoxAddItems(point);
                dic.Add(point, tSocket);
                //接收消息
                Thread th = new Thread(ReceiveMsg);
                th.IsBackground = true;
                th.Start(tSocket);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
                break;
            }
        }
    }

    //接收消息 
    void ReceiveMsg(object o)
    {
        Socket client = o as Socket;
        while (true)
        {
            //接收客户端发送过来的数据
            try
            {
                //定义byte数组存放从客户端接收过来的数据
                byte[] buffer = new byte[1024 * 1024];
                //将接收过来的数据放到buffer中,并返回实际接受数据的长度
                int n = client.Receive(buffer);
                //将字节转换成字符串
                string words = Encoding.UTF8.GetString(buffer, 0, n);
                ShowMsg(client.RemoteEndPoint.ToString() + ":" + words);
            }
            catch (Exception ex)
            {
                if (!client.Connected) ComboBoxRoMoveItems(client.RemoteEndPoint.ToString());
                ShowMsg(ex.Message);
                break;
            }
        }
    }

    delegate void SetTextCallback(string msg);
    public void ShowMsg(string msg)
    {
        if (this.txtLog.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(ShowMsg);
            this.Invoke(d, new object[] { msg });
        }
        else
        {
            this.txtLog.AppendText(msg + "\r\n");
        }
    }

    delegate void SetComboBox(String msg);
    public void ComboBoxAddItems(string msg)
    {
        if (this.cboIpPort.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(ComboBoxAddItems);
            this.Invoke(d, new object[] { msg });
        }
        else
        {
            this.cboIpPort.Items.Add(msg);
        }
    }

    public void ComboBoxRoMoveItems(string msg)
    {
        if (this.cboIpPort.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(ComboBoxRoMoveItems);
            this.Invoke(d, new object[] { msg });
        }
        else
        {
            this.cboIpPort.Items.Remove(msg);
            cboIpPort.SelectedIndex = -1;
        }
    }



    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void label3_Click(object sender, EventArgs e)
    {

    }

    private void Clearbtn_Click(object sender, EventArgs e)
    {
        this.txtLog.Text = "";

    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            string ip = cboIpPort.Text;
            if (cboIpPort.Text.Length > 5)
            {
                byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
                dic[ip].Send(buffer);
                ShowMsg(point.ToString() + ":" + txtMsg.Text);
            }
            else
            {

            }
        }
        catch (Exception ex)
        {
            ShowMsg(ex.Message);
        }


    }
}

}
//客户端===================================

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

namespace socketCWF
{
public partial class FormC : Form
{ //客户端参数
Socket client;
IPAddress ip;
IPEndPoint point;
bool isExits = false;

    public FormC()
    {
        InitializeComponent();
    }
     //定意通讯协议创建socket服务实例
    private void FormC_Load(object sender, EventArgs e)
    {
        ip = IPAddress.Parse(txtIP.Text);
        point = new IPEndPoint(ip, int.Parse(txtPort.Text));

        Thread serverConnetThread = new Thread(ServerConnetThread);
        serverConnetThread.IsBackground = true;
        serverConnetThread.Start();


    }
    //客户端发起连接请求函数
    private void ServerConnet()
    {
        try
        {
            //连接到服务器  
            if (client != null) client.Close();
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(point);
            ShowMsg("连接成功");
            ShowMsg("服务器:" + client.RemoteEndPoint.ToString());
            ShowMsg("客户端:" + client.LocalEndPoint.ToString());
            //连接成功后,就可以接收服务器发送的信息了 
            Thread th = new Thread(ReceiveMsg);
            th.IsBackground = true;
            th.Start();
        }
        catch (Exception ex)
        {
            ShowMsg(ex.Message);
        }
    }

    private void ServerConnetThread()
    {
        while (!isExits)
        {
            if (client == null || !client.Connected)
            {
                ServerConnet();
            }
            Thread.Sleep(5000);
        }
    }

    //接收服务器的消息
    void ReceiveMsg()
    {
        while (true)
        {
            try
            {
                byte[] buffer = new byte[1024 * 1024];
                int n = client.Receive(buffer);
                string s = Encoding.UTF8.GetString(buffer, 0, n);
                ShowMsg(point.ToString() + ":" + s);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
                break;
            }
        }
    }

    delegate void SetTextCallback(string msg);
    //文本框接收服务器信息
    public void ShowMsg(string msg)
    {
        if (this.txtInfo.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(ShowMsg);
            this.Invoke(d, new object[] { msg });
        }
        else
        {
            this.txtInfo.AppendText(msg + "\r\n");
        }
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        //客户端给服务器发消息          
        if (client != null)
        {
            try
            {
                ShowMsg(client.RemoteEndPoint + ":" + txtInfo.Text);
                byte[] buffer = Encoding.UTF8.GetBytes(txtInfo.Text);
                client.Send(buffer);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }


    }
      //清除信息
    private void Clearbtn_Click(object sender, EventArgs e)
    {
        this.txtInfo.Text = "";

    }
}

}

标签:socket,void,练习,System,client,new,using,本机,ShowMsg
From: https://www.cnblogs.com/zhangfengggg/p/17222112.html

相关文章

  • 【转载】Socket 与 TCP 四次挥手(下)
    [转载](https://demonlee.tech/archives/2208002)Socket与TCP四次挥手(下)Demon.Lee2022年08月21日206次浏览本文实践环境:Operat......
  • c语言 循环 函数相关练习
    #include<stdio.h>//1.求任意10个整数的最大数intget_max_1(intarr[]){inti=0;intmax=arr[0];for(i=1;i<10;i++){if(max<ar......
  • c语言学习日志——练习
    T:实现一段字符串从两端逐个向中间移动。code:#define_CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>intmain(){chararr1[]="Welcometo512";chara......
  • MSF练习 - 永恒之蓝
    永恒之蓝漏洞利用一、启动MSFmsfconsole┌──(root㉿kali)-[~]└─#msfconsole                          ......
  • Java字符串基础练习题2(较难)
    ​生成验证码内容:可以是小写字母,也可以是大写字母,还可以是数字​规则: 长度为5 内容中是四位字母,1位数字。 其中数字只有1位,但是可以出现在任意的位置。publicstati......
  • 记websocket调用feign失败
    在http中正常使用的feign接口,在websocket直接失败了,本来以为是没拿到对象,发现其实拿到了。后来发现feign接口如果已经被aop处理过,就会报jdkProxy的错误。修改一下AOP类的......
  • UDP协议类_DatagramSocket——广播代码实现
    广播地址:255.255.255.255 publicclassClientDemo{publicstaticvoidmain(String[]args)throwsIOException{//广播DatagramSocket客户端发送......
  • UDP协议类_DatagramSocket——组播代码实现
    组播地址:224.0.0.0--239.225.225.225,其中224.0.0.0--224.0.0.225为预留的组播地址,我们一般使用224.0.1.0及其之后的地址publicclassClientDemo{publicstaticv......
  • UDP协议类_DatagramSocket
    publicclassClientDemo{publicstaticvoidmain(String[]args)throwsIOException{//DatagramSocket客户端发送数据的步骤//1:创建Data......
  • 使用socket 和 httpURLConnection发起http请求
    publicstaticvoidtest()throwsException{//http://127.0.0.1:8080/logger/userInetAddressinetAddress=InetAddress.getByName("www.baidu.......