You are on page 1of 20

Hng dn lp trnh Socket giao tip TCP client/server trong

C#
2Trong lp trnh, Socket l mt API (Application Programming Interface) cung cp cc phng thc giao tip thng qua
mng.

Cc lp .Net c bn trong lp trnh mng


Cc lp ny c cung cp trong hai namespace System.Net v System.Net.Sockets. Hai namespace ny cha rt nhiu lp
dng trong lp trnh mng, nhng trong phm vi bi vit ta ch quan tm n cc lp sau:

Kt ni Server-Client vi TCP/IP

Khi c chy, server cn c xc nh r a ch IP v s lng nghe trn mt port c th. Server s nm trong trng thi
ny cho n khi client gi n mt yu cu kt ni. Sau khi c server chp nhn, mt connection s hnh thnh cho php
server v client giao tip vi nhau.
C th hn, cc bc tin hnh trn server v client m ta cn thc hin s dng giao thc TCP/IP trong C# (c th chy server
v client trn cng mt my):
Server:
1.

To mt i tng System.Net.Sockets.TcpListener bt u lng nghe trn mt cng cc b.

2.

i v chp nhn kt ni t client vi phng thc AccepSocket(). Phng thc ny tr v mt i


tng System.Net.Sockets.Socket dng gi v nhn d liu.

3.

Thc hin giao tip vi client.

4.

ng Socket.

Thng thng quy trnh ny s c t trong mt vng lp (lp li bc 2) chp nhn nhiu kt ni cng lc (s dng
Thread) hoc cc kt ni ln lt.
Client:
1.

To mt i tng System.Net.Sockets.TcpClient

2.

Kt ni n server vi a ch v port xc nh vi phng thc TcpClient.Connect()

3.

Ly lung (stream) giao tip bng phng thc TcpClient.GetStream().

4.

Thc hin giao tip vi server.

5.

ng lung v socket.

Quy trnh ny c th c minh ha theo m hnh sau:

Example v1: Gi nhn d liu dng byte[]


Lp NetworkStream v Socket cung cp cc phng thc gi v nhn d liu dng mng byte. V vy bn cn phi thc hin
cc bc chuyn i d liu sang dng byte v ngc li. Trong v d sau ti s dng d liu dng vn bn ASCII trong
console, v dng cc lp trong namespace System.Text chuyn i. C hai cch bn c th p dng:
- Dng cc static property ca lp abstract System.Text.Encoding vi cc phng thc GetString() v GetBytes().
- To i tng c kiu XXXEncoding (tha k t System.Text.Encoding). V d: UTF8Encoding, ASCIIEncoding,
Mt v d gi nhn d liu n gin nht s dng TCPListener, Socket (pha server) v TCPClient,NetworkStream (pha
client) dng mng byte vi a ch loop-back 127.0.0.1 trn cng mt my.
To hai d n console l Y2Server v Y2Client vi ni dung sau:
Y2Server.cs (v1):
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class Y2Server {
private const int BUFFER_SIZE=1024;
private const int PORT_NUMBER=9999;
static ASCIIEncoding encoding=new ASCIIEncoding();

public static void Main() {


try {
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpListener listener=new TcpListener(address,PORT_NUMBER);
// 1. listen
listener.Start();
Console.WriteLine("Server started on "+listener.LocalEndpoint);
Console.WriteLine("Waiting for a connection...");
Socket socket=listener.AcceptSocket();
Console.WriteLine("Connection received from " + socket.RemoteEndPoint);
// 2. receive
byte[] data=new byte[BUFFER_SIZE];
socket.Receive(data);
string str=encoding.GetString(data);
// 3. send
socket.Send(encoding.GetBytes("Hello "+str));
// 4. close
socket.Close();
listener.Stop();
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex);
}
Console.Read();
}
}
Y2Client.cs (v1):
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class Y2Client{
private const int BUFFER_SIZE=1024;
private const int PORT_NUMBER=9999;
static ASCIIEncoding encoding= new ASCIIEncoding();

public static void Main() {


try {
TcpClient client = new TcpClient();
// 1. connect
client.Connect("127.0.0.1",PORT_NUMBER);
Stream stream = client.GetStream();
Console.WriteLine("Connected to Y2Server.");
Console.Write("Enter your name: ");
string str = Console.ReadLine();
// 2. send
byte[] data=encoding.GetBytes(str);
stream.Write(data,0,data.Length);
// 3. receive
data =new byte[BUFFER_SIZE];
stream.Read(data,0,BUFFER_SIZE);
Console.WriteLine(encoding.GetString(data));
// 4. Close
stream.Close();
client.Close();
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex);
}
Console.Read();
}
}
kim tra v d, bn chy server trc, ca s console ca server s hin th:
Server started on 127.0.0.1:9999
Waiting for a connection

Tip n cho chy client, nu kt ni thnh cng, server s hin th thm dng thng bo tng t nh sau:
Connection received from 127.0.0.1:2578

Chuyn qua ca s console ca client v nhp tn ca bn vo, nu nhn c d liu, server s gi tr li dng thng ip
Hello [Your Name]
Connected to Y2Server.

Enter your name: Yin Yang


Hello Yin Yang

Ngay sau bc ny, c server v client u thc hin ng kt ni.


(cn tip...)

Cch s dng Socket Lp trnh Socket giao tip TCP client/server lp trnh Client-Server Lp Trnh Socket Client-server vi Network Stream trong C# LP
TRNH SOCKET VI TCP/UDP Lp trnh C# Lp trnh Source code Source code C Source code .net

cng vo Ngy 25/11/2014


h
i
a
s

i
v
i

11 Answers
active

0Example v2: S dng StreamReader v StreamWriter


S tin li hn nu ta s dng StreamReader v StreamWriter gi nhn d liu m khng cn bc chuyn i qua li mng
byte. Cc i tng StreamReader v StreamWriter c th c khi to trc tip t NetworkStream. Thuc tnh AutoFlush
ca StreamWriter thng c t l true t ng gi d liu m khng cn i b m y hoc bn phi gi th cng
phng thc Flush().
V d sau s dng vng lp thc hin gi nhn d liu lin tc gia server/client cho n khi client nhp vo chui exit:
Y2Server.cs (v2):
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Y2Server {
private const int BUFFER_SIZE=1024;
private const int PORT_NUMBER=9999;
static ASCIIEncoding encoding=new ASCIIEncoding();
public static void Main() {
try {
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpListener listener=new TcpListener(address,PORT_NUMBER);
// 1. listen
listener.Start();
Console.WriteLine("Server started on "+listener.LocalEndpoint);
Console.WriteLine("Waiting for a connection...");
Socket socket=listener.AcceptSocket();
Console.WriteLine("Connection received from " + socket.RemoteEndPoint);
var stream = new NetworkStream(socket);
var reader=new StreamReader(stream);
var writer=new StreamWriter(stream);
writer.AutoFlush=true;
while(true)
{
// 2. receive
string str=reader.ReadLine();
if(str.ToUpper()=="EXIT")
{
writer.WriteLine("bye");

break;
}
// 3. send
writer.WriteLine("Hello "+str);
}
// 4. close
stream.Close();
socket.Close();
listener.Stop();
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex);
}
Console.Read();
}
}
Y2Client.cs (v2):
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class Y2Client{
private const int BUFFER_SIZE=1024;
private const int PORT_NUMBER=9999;
static ASCIIEncoding encoding= new ASCIIEncoding();
public static void Main() {
try {
TcpClient client = new TcpClient();
// 1. connect
client.Connect("127.0.0.1",PORT_NUMBER);
Stream stream = client.GetStream();
Console.WriteLine("Connected to Y2Server.");
while(true)
{
Console.Write("Enter your name: ");
string str = Console.ReadLine();
var reader=new StreamReader(stream);
var writer=new StreamWriter(stream);
writer.AutoFlush=true;
// 2. send

writer.WriteLine(str);
// 3. receive
str=reader.ReadLine();
Console.WriteLine(str);
if(str.ToUpper()=="BYE")
break;
}
// 4. close
stream.Close();
client.Close();
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex);
}
Console.Read();
}
}
Bn chy v d ny ging nh v d u tin v g exit vo client thot ng dng.
tr li 25/11/2014

0Cho Qun!mnh xem v d, nhng khi chy trn hai my khc nhau c kt ni Lan th khng c, cho mnh lm th no
giao tip gia hai my qua mng c?(xin li v mnh ang tm hiu v giao tip mng nn hi b stupid!)
tr li 25/11/2014

Vng Lm
20 0 1

Bn xem li a ch IP xem thay i a ch IP cha!


tr li 25/11/2014

Nguyn Tun Anh


990 813 730

Cho a, u tin cho e xin cm n a dnh thi gian vit nhng bi hit rt b ch
Th 2 a cho e cht :) E ang d nh lm phn mm qun l mail (c th l Gmail) th th e phi bt u t u
tr li 25/11/2014

Long Vn Thnh
20 0 43

Bn c th tm hiu v cc c ch gi nhn mail. Trong .NET th h tr cc API v mail rt y v vic to cng d dng.
Bn c th xem mt vi hng dn trn codeproject s dng ASP.NET nh v d sau:
http://www.codeproject.com/Articles/19609/SMTP-Mail-System-Using-ASP-NET-2-0
tr li 25/11/2014

0Cm n a Qun nhiu :)


tr li 25/11/2014

Long Vn Thnh
20 0 43

Bn i, nu d liu l m thanh v hnh nh th sao , VD nh mun chat voice hay webcam trong mt chng trnh chat
mng LAN y ,bn c th ch cho mnh cch thu v pht cc loi d liu c khng
tr li 25/11/2014

HoanokhongTan
20 0 7

@HoanokhongTan
Cc ng dng ny thng dng giao thc UDP c tc nhanh hn.
tr li 25/11/2014

Nguyn Tun Anh


990 813 730

Anh i, cho em hi nu mun gi v nhn arraylist gia Client v Server dng giao thc TCP th phi lm sao?Cm n
anh trc.^^!
tr li 25/11/2014

Mc Nhi
20 0 6

Phng php gi v nhn i tng l chuyn n thnh dng nh phn (binary). Bn dng hai lp BinaryWriter v
BinaryReader (System.IO) gi v nhn d liu, hoc dng trc tip i tng Socket lm iu ny
V d:
+ Server:
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpListener listener=new TcpListener(address, PORT_NUMBER);
listener.Start();
Socket socket=listener.AcceptSocket();
var bytes = ObjectToByteArray(obj);
socket.Send(bytes);
+ Client:

Socket soc =
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
soc.Connect("127.0.0.1", PORT_NUMBER);
byte[] buffer = new byte[1000];
soc.Receive(buffer);
var obj = ByteArrayToObject(buffer);
Hai phng thc ObjectToByteArray() v ByteArrayToObject(), bn c th chm ti y: ^_^
http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Byte-array-to-object.html
v
http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Object-to-byte-array.html

http://hoidapit.com.vn/Questions/ViewQuestions/3137/huong-dan-lap-trinh-socketgiao-tiep-tcp-client-server-trong-c.html

You might also like