当前位置: 首页 > 工具软件 > C++ Sockets > 使用案例 >

Sockets使用

万俟宜修
2023-12-01

服务端

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public bool serviceState = true;//服务状态,停止

 

TcpListener listener;
private void button1_Click(object sender, EventArgs e)
{
IPAddress localAddress = IPAddress.Parse("172.26.87.20");//提供一个协议 ip的一个地址
listener = new TcpListener(localAddress, 1234);
listener.Start();//执行
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
btnStart.Enabled = false;
btnStart.Enabled = true;
}

public void ListenClientConnect()
{
while (serviceState)
{
TcpClient client = listener.AcceptTcpClient();//接受client
byte[] buffer = new byte[client.ReceiveBufferSize];
NetworkStream stream = client.GetStream();//获取网络流
stream.Read(buffer, 0, buffer.Length);
stream.Close();
client.Close();
textBox1.Text = Encoding.Default.GetString(buffer).Trim();
Thread.Sleep(100);

}

}

private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}

客户端

using System.Net.Sockets;

private void NewMethod()
{
TcpClient client = new TcpClient("172.26.87.20", 1234);
NetworkStream p = client.GetStream();
byte[] send = Encoding.Default.GetBytes(textBox1.Text);
p.Write(send, 0, send.Length);
p.Flush();

p.Close();
client.Close();
}

 

转载于:https://www.cnblogs.com/net520/p/7832250.html

 类似资料: