在ubuntu上配置dotnet環境再跑個C#程序做套接字通信
參考微軟官方知識庫
添加存儲庫
sudo add-apt-repository ppa:dotnet/backports
安裝 SDK
sudo apt-get update && sudo apt-get install -y dotnet-sdk-9.0
安裝運行時
安裝ASP.NET Core 運行時
sudo apt-get update && sudo apt-get install -y aspnetcore-runtime-9.0
或者
安裝不包含 ASP.NET Core 支持的 .NET 運行時
sudo apt-get update && sudo apt-get install -y dotnet-runtime-9.0
編個程序測試下
dotnet new console -o SocketServer
Welcome to .NET 9.0!
---------------------
SDK Version: 9.0.107
----------------
Installed an ASP.NET Core HTTPS development certificate.
To trust the certificate, run 'dotnet dev-certs https --trust'
Learn about HTTPS: https://aka.ms/dotnet-https
----------------
Write your first app: https://aka.ms/dotnet-hello-world
Find out what's new: https://aka.ms/dotnet-whats-new
Explore documentation: https://aka.ms/dotnet-docs
Report issues and find source on GitHub: https://github.com/dotnet/core
Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli
--------------------------------------------------------------------------------------
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /home/siit/donetscript/SocketServer/SocketServer.csproj:
Restore succeeded.
反饋信息里給出了一大溜學習資源,這個培養用戶的手法是真不錯。
繼續繼續,CD進路徑。
cd SocketServer
使用Nano打開Program.cs,并寫入以下代碼。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main()
{
int port = 11000;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(localEndPoint);
listener.Listen(10);
Console.WriteLine($"Server is running on port {port}. Accepting connections...");
while (true)
{
Console.WriteLine("Waiting for a client to connect...");
using (Socket handler = listener.Accept())
{
Console.WriteLine("Client connected. Ready to receive messages:");
byte[] buffer = new byte[1024];
while (true)
{
int received = handler.Receive(buffer);
if (received == 0)
{
Console.WriteLine("Client disconnected.");
break;
}
string message = Encoding.ASCII.GetString(buffer, 0, received);
Console.WriteLine("Received: " + message);
string reply = $"Echo: {message}<EOF>";
byte[] replyBytes = Encoding.ASCII.GetBytes(reply);
handler.Send(replyBytes);
}
}
}
}
}
}
然后運行一下
dotnet run
看到反饋:
SocketServer$ dotnet run
Server is running on port 11000. Accepting connections...
Waiting for a client to connect...
然后通過另一臺電腦,使用NetAssist去連接這臺服務器。套接字通信和NetAssist下載看這篇

可以在服務器端看到
Client connected. Ready to receive messages:
客戶端發送Hello,可以看到服務器的Echo。

同時在服務器終端可以看到
Received: Hello
下一步就準備把這段套接字通信的內容和視覺部分程序結合起來,就可以實現外部設備比如機器人或者PLC等觸發視覺拍照獲取坐標信息等內容的交互了。

浙公網安備 33010602011771號