请你担当一位C#程序开发人员提供代码。我的需求是分别设计一个服务端winfrom一个客户端winfrom。首先从客户端发送一个连接申请到服务器192168010端口1024如果服务器没有响应则进行等待如果服务器有相应则发送客户端电脑的计算机名以及IP地址到服务器。服务器端则通过按钮开启监听接收客户端的请求如果接收到请求则把接收到的IP地址以及计算机名称添加进listbox1中
以下是一个简单的示例代码,实现了你的需求:
服务端(Server):
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.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
private TcpListener listener;
private List<string> clientInfoList;
public Form1()
{
InitializeComponent();
clientInfoList = new List<string>();
}
private void btnStart_Click(object sender, EventArgs e)
{
listener = new TcpListener(IPAddress.Parse("192.168.0.10"), 1024);
listener.Start();
// 开始异步接收客户端连接请求
listener.BeginAcceptTcpClient(HandleClientConnect, null);
lblStatus.Text = "正在监听";
}
private void HandleClientConnect(IAsyncResult result)
{
TcpClient client = listener.EndAcceptTcpClient(result);
// 获取客户端的计算机名和IP地址
string clientInfo = $"{client.Client.RemoteEndPoint.ToString()} - {Dns.GetHostEntry(((IPEndPoint)client.Client.RemoteEndPoint).Address).HostName}";
// 添加到列表中
this.Invoke((MethodInvoker)delegate
{
listBox1.Items.Add(clientInfo);
});
listener.BeginAcceptTcpClient(HandleClientConnect, null);
}
}
}
客户端(Client):
using System;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
TcpClient client = new TcpClient();
client.Connect("192.168.0.10", 1024);
// 发送计算机名和IP地址到服务器
string clientInfo = $"{Environment.MachineName} - {Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]}";
byte[] data = Encoding.ASCII.GetBytes(clientInfo);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
client.Close();
}
catch (Exception ex)
{
MessageBox.Show("连接服务器失败:" + ex.Message);
}
}
}
}
以上代码仅作为示例,可能还需要进行一些错误处理和界面调整等。另外,需要在服务端的按钮点击事件中调用 listener.Stop() 来停止监听
原文地址: https://www.cveoy.top/t/topic/iNDR 著作权归作者所有。请勿转载和采集!