[C#] Ví dụ về socket trên C#
Dạo này đang học C# trên trường nên tiện thể viết mấy bài ghi nhớ 😉
Chương trình 1: Nhập tạo 1 server và 1 client. Client gửi các thông tin gethostname, gethosttime, gethostdate đến server, server nhận và trả về tương ứng các giá trị tên, giờ, ngày.
Chúng ta tạo 2 project riêng lẻ với tên là MyServer và MyClient. Khi chạy các bạn nhớ ấn Ctrl + F5 (bỏ chế độ debug thì mới chạy được nhiều project). Trong code mình đã ghi chú tương đối nên các bạn cố gắng theo dõi.
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace MyServer
{
class Program
{
private const int BUFFER_SIZE = 1024;
private const int PORT_NUMBER = 7826;
static ASCIIEncoding encoding = new ASCIIEncoding();
public static void Main()
{
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER);
Console.WriteLine("dang cho client ket noi...");
// tao ra server
Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
// server lang nghe ket noi tu client
server.Bind(iep);
server.Listen(10);
Socket client = server.Accept();
Console.WriteLine("Chap nhan ket noi tu: " + client.RemoteEndPoint.ToString());
byte[] data = new byte[BUFFER_SIZE];
String result = "";
while (true)
{
// nhan du lieu tu client
int rec = client.Receive(data);
// chuyen ve string
string command = encoding.GetString(data, 0, rec);
Console.WriteLine("Client: " + command);
if (command.Equals("gethostname"))
{
// lay ten server
IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint;
IPAddress ipAddress = endPoint.Address;
IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
result = hostEntry.HostName;
}
else if (command.Equals("gethosttime"))
{
// lay thoi gian
result = DateTime.Now.ToString("h:mm:ss tt");
}
else if (command.Equals("gethostdate"))
{
// lay ngay
result= DateTime.Now.ToString("dd:MM:yyyy");
}
else if (command.Equals("quit"))
{
// dong
server.Close();
client.Close();
break;
}
else
{
result = "khong phai lenh dung";
}
// tra ve ket qua cho client
client.Send(encoding.GetBytes(result));
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
}
}
}
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace MyClient
{
class Program
{
private const int BUFFER_SIZE = 1024;
private const int PORT_NUMBER = 7826;
static ASCIIEncoding encoding = new ASCIIEncoding();
public static void Main()
{
try
{
// IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER);
// tao ra client
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// client connect den cong
client.Connect(iep);
String command = "";
while (!command.Equals("quit"))
{
// cho nhap lenh
command = Console.ReadLine();
// gui lenh
client.Send(encoding.GetBytes(command));
byte[] data = new byte[BUFFER_SIZE];
int rec = client.Receive(data);
Console.WriteLine("server: " + encoding.GetString(data, 0, rec));
}
client.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
}
}
}
Chương trình 2: Client gửi 1 tên file lên server, server kiểm tra xem file đó có tồn tại không, nếu tồn tại thì cho phép client downlod, nếu không thì thông báo không tồn tại file cho client. (Lưu ý nếu chỉ nhập tên file thì server sẽ tìm ở thư mục bin/Debug/)
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace MyServer
{
class Program
{
private const int BUFFER_SIZE = 1024;
private const int PORT_NUMBER = 7826;
static ASCIIEncoding encoding = new ASCIIEncoding();
public static void Main()
{
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER);
Console.WriteLine("dang cho client ket noi...");
// tao ra server
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// server lang nghe ket noi tu client
server.Bind(iep);
server.Listen(10);
Socket client = server.Accept();
Console.WriteLine("Chap nhan ket noi tu: " + client.RemoteEndPoint.ToString());
byte[] data = new byte[BUFFER_SIZE];
// lap vo han
while (true)
{
// nhan du lieu tu client
int rec = client.Receive(data);
// chuyen ve string
string fileName = encoding.GetString(data, 0, rec);
Console.WriteLine("Client: " + fileName);
// neu file ton tai
if (File.Exists(fileName))
{
// gui thong bao la co tim thay file
client.Send(encoding.GetBytes("yes"));
// gui file xuong client
byte[] fileData = File.ReadAllBytes(fileName);
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] servertData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(servertData, 0);
fileNameByte.CopyTo(servertData, 4);
fileData.CopyTo(servertData, 4 + fileNameByte.Length);
client.Send(servertData);
Console.WriteLine("Da gui file " + fileName + " den client!");
client.Close();
// thoat
break;
}
// khong tim thay file
else
{
// gui thong bao khong tim thay file
client.Send(encoding.GetBytes("no"));
Console.WriteLine("khong thay file");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
}
}
}
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace MyClientSendFile
{
class Program
{
private const int BUFFER_SIZE = 1024;
private const int PORT_NUMBER = 7826;
static ASCIIEncoding encoding = new ASCIIEncoding();
public static void Main()
{
try
{
// IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER);
// tao ra client
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// client connect den cong
client.Connect(iep);
// lap vo han
while (true)
{
// nhap file can tai xuong
Console.Write("Nhap file muon download: ");
String fileName = Console.ReadLine();
// gui ten file len server
client.Send(encoding.GetBytes(fileName));
// nhan thong bao co tim thay hay khong
byte[] data = new byte[BUFFER_SIZE];
int rec = client.Receive(data);
String check = encoding.GetString(data, 0, rec);
// neu tim thay thi thuc hien viec nhan file
if (check.Equals("yes"))
{
byte[] serverData = new byte[1024 * 5000];
int receivedBytesLen = client.Receive(serverData);
int fileNameLen = BitConverter.ToInt32(serverData, 0);
BinaryWriter bWrite = new BinaryWriter(File.Open(fileName, FileMode.Append));
bWrite.Write(serverData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
Console.WriteLine("Da nhan file " + fileName + " tu server!");
bWrite.Close();
// thoat
break;
}
// neu khong tim thay thi bat nhap lai
else
{
Console.WriteLine("Server khong co file " + fileName);
}
}
client.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
}
}
}



Chào bạn, bạn có thể cho mình hỏi tài liệu học tiếng việt về lập trình mạng, hoặc nguồn học trên mạng ở đâu?
Cảm ơn nhiều!
Cái này mình chỉ google thôi, và toàn google tiếng anh hết bạn ah
anh cho em hỏi chỗ ipe của client là khi truyền IPAddress vào là IP của client hay server vậy?
Của server bạn nhé, đang cần kết nối đến server mà.
Cho mình hỏi, ví dụ như sàn giao dịch tiền điện tử binance.com họ cho user viết tool để trade, cung cấp data real time, ra lệnh mua bán bằng APi. Cho mình hỏi có thể dùng C# để viết tool, soft hay không và cần dùng những soft hay công cụ phụ trợ nào nữa. Cảm ơn!
Cái này mình không rõ bạn ah.