C#向特定的端口发送信息,并在相应的端口接收数据

2024-12-03 04:13:03
推荐回答(3个)
回答1:

用tcp或者udp都可以 下面是udp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace liaotian
{
public partial class Form1 : Form
{
private UdpClient uc;
private IPEndPoint iep;
private Thread th;
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
uc = new UdpClient(8888);
}

private void button1_Click(object sender, EventArgs e)
{
iep = new IPEndPoint(IPAddress.Parse(ip.Text), 8888);
string temp = jieshou.Text;
byte[] b = Encoding.UTF8.GetBytes(temp);
uc.Send(b, b.Length, iep);//发送数据
}
private void listen()//监听
{
while (true)
{
string text = Encoding.UTF8.GetString(uc.Receive(ref iep));//返回接受的数据
jieshou.Items.Add(text + "\n");
}
}

private void Form1_Load(object sender, EventArgs e)
{
iep = new IPEndPoint(IPAddress.Parse(ip.Text), 8888);
th = new Thread(new ThreadStart(listen));//线程
th.IsBackground = true;
th.Start();
}
}
}

回答2:

TCP

回答3:

网上很多例子