Tải bản đầy đủ (.pdf) (23 trang)

Lập Trinh sockets,Thực hành SOCKETS

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (878.13 KB, 23 trang )

THỰC HÀNH TUẦN 3
SOCKETS
1. Lớp IP Address: lớp thể hiện địa chỉ IP. Địa chỉ là một tập hợp gồm 4 con số có giá trị từ
0 đến 255 và được cách nhau bởi dấu chấm.
IPAddress ipadd = IPAddress.Parse(“127.0.0.1”);

2. Lớp IPEndpoint: lớp chứa đựng cả IPAddress và số hiệu cổng
IPEndPoint RemoteIpEndPoint = new IPEndPoint(ipadd, 8080);\

3. Kết nối UDP
Giao thức UDP là giao thức phi kết nối, nói cách khác không cần thiết lập kết nối giữa hai
bên khi tiến hành trao đổi thông tin.
Giao thức không tin cậy bằng giao thức TCP, nhưng tốc độ lại nhanh và dễ cài đặt. Ngoài
ra có thể gửi các gói tin quảng bá (broadcast) đồng thời cho nhiều máy.
Sử dụng lớp UDPClient để thực hiện kết nối UDP giữa hai máy hoặc giữa 1 máy với nhiều
máy.
Bài tập mẫu: (Chương 3_bài 1)
Thực hiện gởi và nhận dữ liệu giữa hai bên sử dụng giao thức UDP

Thực Hành Tuần 3

Trang 1


Gợi ý:
Bên A – gọi là UDP client, cần kết nối đến bên B – UDP server để gởi dữ liệu. Trong bài tập
này, ta cho dữ liệu là chuỗi “Hello World?”
Sự kiện cho nút Send:
private void button1_Click(object sender, EventArgs e)
{
//Tạo kết nối UDP


UdpClient udpClient = new UdpClient();
//Lấy địa chỉ IP từ textbox và chuyển thành kiểu IPAddress
IPAddress ipadd = IPAddress.Parse(tbHost.Text);
//Thực hiện kết nối tới UDP server bằng địa chỉ IP address vừa gõ
và port 8080
udpClient.Connect(ipadd, 8080);
//Do ý đồ muốn gởi dữ liệu là “Hello World?” sang bên nhận. Nên cần
chuyển chuỗi
Hello World sang kiểu byte
Byte[] sendBytes = Encoding.ASCII.GetBytes("Hello World?");
//Gởi dữ liệu
udpClient.Send(sendBytes, sendBytes.Length);
}

Bên B:
-

Sử dụng ListBox để nhận dữ liệu từ bên A gởi.

-

Bắt sự kiện xảy ra khi Form được Load lên

 Khai báo các thành phần:
private System.Windows.Forms.ListBox lbConnections;
private void InitializeComponent()
{
this.lbConnections = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//

// lbConnections
//
this.lbConnections.FormattingEnabled = true;
this.lbConnections.ItemHeight = 16;
this.lbConnections.Location = new System.Drawing.Point(14, 18);
this.lbConnections.Name = "lbConnections";
this.lbConnections.Size = new System.Drawing.Size(353, 292);
Thực Hành Tuần 3

Trang 2


this.lbConnections.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(379, 322);
this.Controls.Add(this.lbConnections);
this.Font = new System.Drawing.Font("Microsoft Sans Serif",
9.75F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}


 Hàm serverThread: đón nhận dữ liệu từ bên A gởi sang và hiện lên ListBox
public void serverThread()
{
UdpClient udpClient = new UdpClient(8080);
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any,
0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
string mess = RemoteIpEndPoint.Address.ToString() + ":" +
returnData.ToString();
InfoMessage(mess);
}
}

Giải thích:
-

Tại bên nhận, khai báo kết nối UDP với số hiệu cổng là 8080 và địa chỉ IPAdress là
Any.

-

IPAddress.Any nghĩa là socket này có thể listen từ bất kì địa chỉ ip nào trong port
8080.

Sự kiện load Form: Tạo một thread để chạy hàm nhận dữ liệu từ bên gởi.
private void Form1_Load(object sender, EventArgs e)

{
Thực Hành Tuần 3

Trang 3


Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
thdUDPServer.Start();
}

4. Kết nối TCP
Để đảm bảo độ tin cậy trong các ứng dụng mạng, người ta sử dụng giao thức TCP _ một
giao thức có kết nối
Bài 1: (Chương 3_ bài 3 single thread)
Viết chương trình lắng nghe dữ liệu từ dịch vụ Telnet sử dụng kết nối TCP ( sử dụng lớp
Socket) với mô tả sau:
1. Chạy chương trình
2. Nhấn nút Listen
3. Mở CMD gõ lệnh: telnet <IP của máy> 8080
4. Vào màn hình telnet, gõ thông điệp tùy ý, sau khi kết thúc, đóng cửa sổ telnet lại thì
thông báo trên sẽ được chương trình nhận và hiện lên form.
5. Xem hình mẫu.

Thực Hành Tuần 3

Trang 4


Gợi ý:
Bật telnet trong win 7: />Để có thể telnet đến địa chỉ IP của máy tại cổng 8080, ta phải mở port 8080 lắng nghe kết nối

TCP đến port 8080, do đó khi nhấn nút Listen có nghĩa là ta đang thực hiện lắng nghe kết nối
tại địa chỉ IP của máy và cổng là 8080
Sự kiện cho nút Listen:
private void btnListen_Click(object sender, EventArgs e)
{
int bytesReceived = 0;
// Khởi tạo mảng byte nhận dữ liệu
byte[] recv = new byte[1];
// Tạo socket bên gởi
Socket clientSocket;
// Tạo socket bên nhận, socket này là socket lắng nghe các kết nối
tới nó tại địa chỉ IP của máy và port 8080. Đây là 1 TCP/IP
socket.
//AddressFamily: trả về họ địa chỉ của địa chỉ IP hiện hành. Ở đây
là địa chỉ Ipv4 nên chọn AddressFamily.InterNetwork
//SocketType: kiểu kết nối socket, ở đây dùng luồng Stream để nhận
dữ liệu
//ProtocolType: sử dụng giao thức kết nối nào, ở đây sử dụng kết
nối TCP
// Ba tham số của hàm đi với nhau khi ta thực hiện kết nối TCP.
Socket listenerSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp
);
// Dns.gethostName: lấy về tên của máy tính cục bộ
//Dns.GethostbyName (Dns.gethostName): trả về thông tin địa chỉ
IP, nó gồm 1 mảng các alias với địa chỉ IP đi kèm
IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
// IPHost.AddressList[0]: lấy địa chỉ IP đầu tiên trong mảng các

alias và địa chỉ IP đi kèm

Thực Hành Tuần 3

Trang 5


IPEndPoint ipepServer = new
IPEndPoint(IPHost.AddressList[0], 8080);
// Gán socket lắng nghe tới địa chỉ IP của máy và port 8080
listenerSocket.Bind(ipepServer);
// bắt đầu lắng nghe. Socket.Listen(int backlog)
// với backlog: là độ dài tối đa của hàng đợi các kết nối đang chờ
xử lý
listenerSocket.Listen(-1);
//Đồng ý kết nối
clientSocket = listenerSocket.Accept();
Nhận dữ liệu
if (clientSocket.Connected)
{
do
{
bytesReceived = clientSocket.Receive(recv);
tbStatus.Text += Encoding.ASCII.GetString(recv);
} while (bytesReceived != 0);
}
}

Bài 2 ( chuong3_bai4)
Viết chương trình in ra địa chỉ Loopback, Broadcast, None, Any và kiểm tra địa chỉ IP local có

phải là địa chỉ IP Loopback không?

Thực Hành Tuần 3

Trang 6


Gợi ý:
static void Main(string[] args)
{
IPAddress test1 = IPAddress.Parse("192.168.1.1");
IPAddress test2 = IPAddress.Loopback;
IPAddress test3 = IPAddress.Broadcast;
IPAddress test4 = IPAddress.Any;
IPAddress test5 = IPAddress.None;
//IPHostEntry ihe =
//
Dns.GetHostByName(Dns.GetHostName());
IPHostEntry ihe = Dns.GetHostEntry(Dns.GetHostName());
IPAddress myself = ihe.AddressList[0];
if (IPAddress.IsLoopback(test2))
Console.WriteLine("The Loopback address is: {0}",
test2.ToString());
else
Console.WriteLine("Error obtaining the loopback address");
Console.WriteLine("The Local IP address is: {0}\n",
myself.ToString());
if (myself == test2)
Console.WriteLine("The loopback address is the same as local
address.\n");

else
Console.WriteLine("The loopback address is not the local
address.\n");
Console.WriteLine("The test address is: {0}",
test1.ToString());
Console.WriteLine("Broadcast address: {0}",
test3.ToString());
Console.WriteLine("The ANY address is: {0}",
test4.ToString());
Console.WriteLine("The NONE address is: {0}",
test5.ToString());
Console.ReadLine();
}

Bài 3: (Chuong 3 _ bai 6)
Viêt chương trình thực hiện các yêu cầu sau:
-

Khởi tạo một địa chỉ IP 127.0.0.1 với cổng 8000.

-

Khởi tạo một socket có tên là test, kết nối TCP

-

In ra các thuộc tính Address Family, SocketType, Protocol Type của socket test

-


Kiểm tra xem socket có đang ở chế độ Blocking hay không?

Thực Hành Tuần 3

Trang 7


-

Set Blocking = false? Kiểm tra lại chế độ Blocking, Connected sau khi set blocking
bằng false.

-

Gán địa chỉ IP + port đến socket.

-

In ra địa chỉ IP + port vừa được gán tới socket.

Gợi ý:
static void Main(string[] args)
{
IPAddress ia = IPAddress.Parse("127.0.0.1");
IPEndPoint ie = new IPEndPoint(ia, 8000);
Socket test = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("AddressFamily: {0}",
test.AddressFamily);
Console.WriteLine("SocketType: {0}",

test.SocketType);
Console.WriteLine("ProtocolType: {0}",
test.ProtocolType);
Console.WriteLine("Blocking: {0}", test.Blocking);
test.Blocking = false;
Console.WriteLine("new Blocking: {0}", test.Blocking);
Console.WriteLine("Connected: {0}", test.Connected);
test.Bind(ie);
IPEndPoint iep = (IPEndPoint)test.LocalEndPoint;
Thực Hành Tuần 3

Trang 8


Console.WriteLine("Local EndPoint: {0}",
iep.ToString());
test.Close();
Console.ReadLine();
}

Bài 4 (Chương 3_ bai 5)
Viêt chương trình thực hiện các yêu cầu sau:
-

Khởi tạo một địa chỉ IP 127.0.0.1 với cổng 8000.

-

In ra địa chỉ IP và số hiệu cổng trên.


-

In ra các thuộc tính Address Family, địa chỉ và cổng.

-

In ra số hiệu cổng tối thiểu và tối đa.

-

Thay đổi số hiệu cổng thành 80

-

In ra địa chỉ IP và số hiệu cổng đã được thay đổi.

-

In ra SocketAdress.

Gợi ý:
static void Main(string[] args)
Thực Hành Tuần 3

Trang 9


{
IPAddress test1 = IPAddress.Parse("192.168.1.1");
IPEndPoint ie = new IPEndPoint(test1, 8000);

Console.WriteLine("The IPEndPoint is: {0}",
ie.ToString());
Console.WriteLine("The AddressFamily is: {0}",
ie.AddressFamily);
Console.WriteLine("The address is: {0}, and the port is:
{1}\n", ie.Address, ie.Port);
Console.WriteLine("The min port number is: {0}",
IPEndPoint.MinPort);
Console.WriteLine("The max port number is: {0}\n",
IPEndPoint.MaxPort);
ie.Port = 80;
Console.WriteLine("The changed IPEndPoint value is: {0}",
ie.ToString());
SocketAddress sa = ie.Serialize();
Console.WriteLine("The SocketAddress is: {0}",
sa.ToString());
Console.ReadLine();
}

Bài 5: (Chương 3_bài 8)
Viết chương trình lắng nghe dữ liệu từ dịch vụ Telnet sử dụng kết nối TCP với mô tả sau:
1. Chạy chương trình
2. Một màn hình đen hiện ra chữ “Waiting for a client…”
3. Mở CMD gõ lệnh: telnet <IP của máy> 9050
4. Tại màn hình telnet hiện chữ “Welcome to my test sever”.
5. Tại màn hình chương trình hiện chữ “Connect with địa chỉ IP at port số hiệu cổng”
6. Vào màn hình telnet, gõ thông điệp tùy ý thì lập tức bên màn hình chương trình hiện y
chang vậy
7. Đóng màn hình telnet.
8. Màn hình chương trình hiện ra chữ “ Disconnect at địa chỉ IP” và chương trình đóng

lại
9. Xem hình mô tả.

Thực Hành Tuần 3

Trang 10


Gợi ý:
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsock = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep =
(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",
clientep.Address, clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,
Thực Hành Tuần 3


Trang 11


SocketFlags.None);
while (true)
{
data = new byte[1024];
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine(
Encoding.ASCII.GetString(data, 0, recv));
}
Console.WriteLine("Disconnected from {0}",
clientep.Address);
client.Close();
newsock.Close();
}

Bài tập về nhà
Viết chương trình gửi và nhận dữ liệu sử dụng TCP Client và TCP Listener.

Tra cưu lý thuyết:
 Bật telnet trong win 7: /> system.net.sockets: /> Socket: /> DNS: /> IPHostEntry: />
Thực Hành Tuần 3

Trang 12


 IPAddress: /> IPEndpoint : />

Thực Hành Tuần 3

Trang 13


Server :

using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Net;

System.Net.Sockets;
System.Threading;
System.IO;
AxMSTSCLib;

namespace Server
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
List<Socket> listClient = new List<Socket>();
Socket client;
TcpListener listen;
Thread t;
private Stream stmReader = null;
private Stream stmWriter = null;
private void btn_open_Click(object sender, EventArgs e)
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);
listen = new TcpListener(ipe);
listen.Start();
MessageBox.Show("Đang Chờ Kết Nối Từ Client");
t = new Thread(ketnoi);
t.Start();
}
public void ketnoi()

{
while (true)
{
client = listen.AcceptSocket();

Thực Hành Tuần 3

Trang 14


listClient.Add(client);
//MessageBox.Show("Client Kết Nối Thành Công");
//tao 1 tuyen moi de nhan du lieu tu client khi co ket noi moi
t = new Thread(nhandulieu);
t.Start(client);

string s = "Chào mừng 11520010 " + " đã kết nối đến máy chủ" + "\r\n";
byte[] data = new byte[1024];
data = Encoding.UTF8.GetBytes(s);
client.Send(data, data.Length, SocketFlags.None);
}
}
public void nhandulieu(object ojb)
{
Socket sock = (Socket)ojb;
while (true)
{
try
{
// //nhan du lieu tu client

byte[] data = new byte[1024];
int recv = sock.Receive(data);
string s = Encoding.UTF8.GetString(data, 0, recv);
rtb_hienthi.Text += s + "\r\n";
rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length;
rtb_hienthi.ScrollToCaret();
//tra du lieu ve cac client
byte[] data1 = new byte[1024];
data1 = Encoding.UTF8.GetBytes(s);
foreach (Socket i in listClient)
{
i.Send(data1, data1.Length, SocketFlags.None);
}
}
catch
{
continue;
}
}
}
private void btn_send_Click(object sender, EventArgs e)
{
byte[] data = new byte[1024];
data = Encoding.UTF8.GetBytes("Server : "+txt_chat.Text);
foreach (Socket i in listClient)
{
i.Send(data, data.Length, SocketFlags.None);
} rtb_hienthi.Text +="Server : "+ txt_chat.Text + "\r\n";
rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length;
rtb_hienthi.ScrollToCaret();

}

public byte[] filebyte(string filename)

Thực Hành Tuần 3

Trang 15


{
byte[] file = File.ReadAllBytes(filename);
return file;
}
//bool SaveData(byte[] Data)
//{
//
BinaryWriter Writer = null;
//
string Name = "book.txt";
//
//
//
//
//
//
//
//
//
//
//


try
{
Writer = new BinaryWriter(File.OpenWrite(Name));
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
return false;
}

//
return true;
//}
private void btn_sendfile_Click(object sender, EventArgs e)
{
//byte[] data = new byte[1024];
//data = Encoding.UTF8.GetBytes("Server : Send"+txtFileName.Text);
//foreach (Socket i in listClient)
//{
//
i.Send(data, data.Length, SocketFlags.None);
//}
//OpenFileDialog fileDialog = new OpenFileDialog();
//if (fileDialog.ShowDialog() == DialogResult.OK)
//{
//
string s = fileDialog.FileName;

//
string[] a = s.Split('.');
//
byte[] data1 = new byte[1024];
//
data = Encoding.UTF8.GetBytes(a[1]);
//
client.Send(data);
//
// client.Send(filebyte(fileDialog.FileName));
//}
//}
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string s = fileDialog.FileName;
client.SendFile(s);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}

Thực Hành Tuần 3

Trang 16


private void button1_Click(object sender, EventArgs e)
{

IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);
listen = new TcpListener(ipe);
listen.Start();
//MessageBox.Show("Đang Chờ Kết Nối Từ Client");
t = new Thread(ketnoi);
t.Start();
}
//private void btn_brow_Click(object sender, EventArgs e)
//{
//
OpenFileDialog fileDialog = new OpenFileDialog();
//
if (fileDialog.ShowDialog(this) == DialogResult.OK)
//
{
//
txtFileName.Text = fileDialog.FileName;
//
}
//}
//private void toolStripButton1_Click(object sender, EventArgs e)
//{

//
//
//
//
//
//


for (int i = 0; i < lsb_1.Items.Count; i++)
{
string s = lsb_1.SelectedItem.ToString();
//rdp.Server = s;
//rdp.Connect();
//MessageBox.Show(s);

//
//
//
//
//
//
//
//
//}

//}
AxMsRdpClient7 rdp = new AxMsRdpClient7();
rdp.AdvancedSettings6.RDPPort = Convert.ToInt16(s);
//rdp.UserName = username;
//IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
//secured.ClearTextPassword = password;
rdp.Connect();
}

}
}

Thực Hành Tuần 3


Trang 17


using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.IO;
System.Net;
System.Net.Sockets;

namespace Server
{

public partial class SendFile : Form
{
public SendFile()
{
InitializeComponent();
}
public string GetIP()
{
string name = Dns.GetHostName();
IPHostEntry entry = Dns.GetHostEntry(name);
IPAddress[] addr = entry.AddressList;
if (addr[1].ToString().Split('.').Length == 4)
{
return addr[1].ToString();
}
return addr[2].ToString();
}
public void btn_send_Click(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader(txtFileName.Text);
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(new IPEndPoint(IPAddress.Parse(GetIP()), 8085));
byte[] buffer = new byte[1500];
long bytesSent = 0;
while (bytesSent < sr.BaseStream.Length)
{
int bytesRead = sr.BaseStream.Read(buffer, 0, 1500);
tcpClient.GetStream().Write(buffer, 0, bytesRead);

listBox1.Items.Add(bytesRead + " bytes sent.");
bytesSent += bytesRead;
}

Thực Hành Tuần 3

Trang 18


tcpClient.Close();
listBox1.Items.Add("finished");
Console.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void pro_1_Click(object sender, EventArgs e)
{
}
private void btn_brow_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.ShowDialog();
txtFileName.Text = op.FileName;
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
}

}
}

Thực Hành Tuần 3

Trang 19


Client:

using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;

System.Windows.Forms;
System.Threading;
System.Net;
System.Net.Sockets;
System.IO;

namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
Thread truyen;
Socket client;
private void btn_connec_Click(object sender, EventArgs e)
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(txt_ip.Text), 100);
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
client.Connect(ipe);
//MessageBox.Show("Đã Kết Nối Đến Server");
byte[] data = new byte[1024];
int recv = client.Receive(data);
rtb_hienthi.Text = Encoding.UTF8.GetString(data, 0, recv);
truyen = new Thread(new ThreadStart(nhandulieu));
truyen.Start();
}

public void nhandulieu()
{

while (true)
{
byte[] data = new byte[1024*50000];
int recv = client.Receive(data);
string s = Encoding.UTF8.GetString(data, 0, recv);

Thực Hành Tuần 3

Trang 20


//string m = Encoding.UTF8.GetString(data, 0, recv);
rtb_hienthi.Text += s + "\r\n";
rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length;
rtb_hienthi.ScrollToCaret();
}
}
private void btn_send_Click(object sender, EventArgs e)
{
//txt_name.ReadOnly = true;
byte[] data = new byte[1024];
data = Encoding.UTF8.GetBytes("11520010" + " : " + txt_chat.Text);
client.Send(data, data.Length, SocketFlags.None);
rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length;
rtb_hienthi.ScrollToCaret();
}
//private void btn_create_Click(object sender, EventArgs e)

//{
//
txt_name.Enabled = false;
//
txt_name.ReadOnly = true;
//
btn_create.Enabled = false;
//
//txt_name = "11520010";
//}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
//private Stream stmReader = null;
//private NetworkStream nwkStream = null;
//private Stream stmWriter = null;
//private TcpClient tcpClient = null;
//bool SaveData(byte[] Data)
//{
//
BinaryWriter Writer = null;
//
string Name = "book.txt";
//
//
//
//
//
//

//
//
//
//
//

try
{
Writer = new BinaryWriter(File.OpenWrite(Name));
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
return false;
}

//
return true;
//}
//private void btn_nhanfile_Click(object sender, EventArgs e)
//{

Thực Hành Tuần 3

Trang 21


//

//
//
//
//

//lay het du lieu trong file
byte[] data = new byte[1024 * 50000];
int recv = client.Receive(data);
string s = Encoding.UTF8.GetString(data, 0, recv);
//

//
//
//
//
//
//}

byte[] data1 = new byte[1024 * 50000];
data1 = Encoding.UTF8.GetBytes(s);
//int a = client.Receive(data1);
File.WriteAllBytes("bb.", data1);
MessageBox.Show("nhan thanh cong");

}
}

Thực Hành Tuần 3

Trang 22



using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Windows.Forms;

namespace Client
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

Thực Hành Tuần 3


Trang 23



×