0% found this document useful (0 votes)
15 views12 pages

12

The document is a C# Windows Forms application that implements a server-client model supporting multiple communication protocols including TCP, UDP, COM, and HTTP. It features functionalities for connecting to clients, receiving data, and displaying it in a GUI, as well as saving the received data to a SQL database. The application also includes error handling and user notifications for various operations.

Uploaded by

21013328
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views12 pages

12

The document is a C# Windows Forms application that implements a server-client model supporting multiple communication protocols including TCP, UDP, COM, and HTTP. It features functionalities for connecting to clients, receiving data, and displaying it in a GUI, as well as saving the received data to a SQL database. The application also includes error handling and user notifications for various operations.

Uploaded by

21013328
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Windows.Forms.DataVisualization.Charting;
using System.Xml;

namespace NguyenThiCuc_Lab10
{
public partial class Form1 : Form
{
string url = "";
Boolean autorequest = false;
string InputData = String.Empty;
delegate void SetTextCallback(string text);
string CommandDataTime = String.Empty;
string dataReceive = string.Empty;
UdpClient clientsock, serversock;

Boolean startServer = false;


string ipclient;
int portServer;
IPEndPoint remoteEP;
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-8V3UE63\
TEW_SQLEXPRESS;Initial Catalog=NTPhuongAnh_DTVT2_K15;Integrated Security=True");
static int i = 0;
static int countChar = 0;
float temp = 0;
float light = 0;

public Form1()
{
InitializeComponent();
timer1.Start();
comboBox1.Items.AddRange(new string[] { "COM", "TCP", "UDP", "HTTP" });
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

private void SetText(string text)


{
if (InvokeRequired) this.Invoke(new Action(() => getData.Text = text));
else getData.AppendText(text + Environment.NewLine);
}

private bool IsPortInUse(int port)


{
IPGlobalProperties ipGlobalProperties =
IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners();

foreach (IPEndPoint endPoint in tcpEndPoints)


{
if (endPoint.Port == port)
{
return true;
}
}
return false;
}

private void acceptClient()


{
try
{
if (comboBox1.SelectedItem.ToString() == "TCP")
{
// Khởi tạo socket TCP
IPEndPoint iep = new IPEndPoint(IPAddress.Any, portServer);
Serversock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

if (IsPortInUse(portServer))
{
MessageBox.Show("Port " + portServer + " is already in
use.");
return;
}

Serversock.Bind(iep);
Serversock.Listen(1);
MessageBox.Show("Server TCP đang lắng nghe trên cổng " +
portServer);

while (startServer)
{
try
{
Clientsock = Serversock.Accept();
IPEndPoint Clientep =
(IPEndPoint)Clientsock.RemoteEndPoint;
string ipClient = Clientep.Address.ToString();
int portClient = Clientep.Port;

ipc.Invoke((MethodInvoker)delegate
{
ipc.Text = ipClient + ":" + portClient;
});

Thread readClient = new Thread(ServerTCP);


readClient.IsBackground = true;
readClient.Start();
}
catch (Exception ex)
{
MessageBox.Show("Lỗi khi chấp nhận kết nối TCP: " +
ex.Message);
serversock.Close();
}
}
}
else if (comboBox1.SelectedItem.ToString() == "UDP")
{
// Khởi tạo UDP Server
serversock = new UdpClient(portServer);
remoteEP = new IPEndPoint(IPAddress.Any, portServer);
MessageBox.Show("Server UDP đang lắng nghe trên cổng " +
portServer);

while (startServer)
{
try
{
byte[] data = serversock.Receive(ref remoteEP);
string receivedData = Encoding.ASCII.GetString(data);

if (!string.IsNullOrEmpty(receivedData))
{
Invoke((MethodInvoker)delegate
{
getData.AppendText(receivedData +
Environment.NewLine);
});

ipclient = remoteEP.Address.ToString();
int portclient = remoteEP.Port;

Invoke((MethodInvoker)delegate
{
ipc.Text = ipclient + ":" + portclient;
});

ParseAndDisplayData(receivedData);
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi nhận dữ liệu UDP: " + ex.Message);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi chung khi chạy acceptClient: " + ex.Message);
}
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)


{
string selectedProtocol = comboBox1.SelectedItem.ToString();
switch (selectedProtocol)
{
case "COM":
ConnectCOM();
ReceiveCOMData();
break;
case "TCP":
ConnectTCP();
ReceiveTCPData();
break;
case "UDP":
ConnectUDP();
ReceiveUDPData();
break;
case "HTTP":
ConnectHTTP();
ReceiveHTTPData();
break;
}
}
private void ConnectCOM()
{
try
{
serialPort = new SerialPort("COM3", 9600, Parity.None, 8,
StopBits.One);
serialPort.Open();
MessageBox.Show("Kết nối COM thành công");
}
catch (Exception ex)
{
MessageBox.Show("Lỗi COM: " + ex.Message);
}
}

private void ReceiveCOMData()


{
try
{
if (serialPort != null && serialPort.IsOpen)
{
serialPort.DataReceived += (s, e) =>
{
string receivedData = serialPort.ReadLine();
SetText(receivedData);
ParseAndDisplayData(receivedData);
};
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi nhận dữ liệu COM: " + ex.Message);
}
}

private void ConnectTCP()


{
try
{
tcpClient = new TcpClient("127.0.0.1", 12345);
MessageBox.Show("Kết nối TCP thành công");
}
catch (Exception ex)
{
MessageBox.Show("Lỗi TCP: " + ex.Message);
}
}

private void ReceiveTCPData()


{
try
{
NetworkStream stream = tcpClient.GetStream();
byte[] buffer = new byte[1024];
stream.BeginRead(buffer, 0, buffer.Length, (IAsyncResult ar) =>
{
int bytesRead = stream.EndRead(ar);
if (bytesRead > 0)
{
string receivedData = Encoding.ASCII.GetString(buffer, 0,
bytesRead);
Invoke((MethodInvoker)delegate
{
SetText(receivedData);
ParseAndDisplayData(receivedData);
});
}
ReceiveTCPData(); // Tiếp tục lắng nghe dữ liệu
}, null);
}
catch (Exception ex)
{
MessageBox.Show("Lỗi nhận dữ liệu TCP: " + ex.Message);
}
}

private void ConnectUDP()


{
try
{
udpClient = new UdpClient();
udpClient.Connect("192.168.137.1", 1405);
MessageBox.Show("Kết nối UDP thành công");
}
catch (Exception ex)
{
MessageBox.Show("Lỗi UDP: " + ex.Message);
}
}

private void ReceiveUDPData()


{
Thread receiveThread = new Thread(() =>
{
while (true)
{
try
{
byte[] data = udpClient.Receive(ref remoteEP);
string receivedData = Encoding.ASCII.GetString(data);
Invoke((MethodInvoker)delegate
{
SetText(receivedData);
ParseAndDisplayData(receivedData);
});
}
catch (Exception ex)
{
MessageBox.Show("Lỗi nhận dữ liệu UDP: " + ex.Message);
break;
}
}
})
{
IsBackground = true
};
receiveThread.Start();
}

private void ConnectHTTP()


{
try
{
using (WebClient client = new WebClient())
{
string response = client.DownloadString("http://example.com");
MessageBox.Show("HTTP Response: " + response);
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi HTTP: " + ex.Message);
}
}

private void ReceiveHTTPData()


{
try
{
using (WebClient client = new WebClient())
{
string response =
client.DownloadString("http://example.com/api/data");
SetText(response);
ParseAndDisplayData(response);
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi nhận dữ liệu HTTP: " + ex.Message);
}
}

private void Form1_Load(object sender, EventArgs e)


{
// TODO: This line of code loads data into the
'nguyenThiCuc_21013328_Lab10DataSet.BTH10' table. You can move, or remove it, as
needed.
this.bTH10TableAdapter.Fill(this.nguyenThiCuc_21013328_Lab10DataSet.BTH10);
dataTable = new DataTable();
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Temp", typeof(float));
dataTable.Columns.Add("Light", typeof(float));
dataTable.Columns.Add("TimeCreat", typeof(string));

// Gán DataTable vào DataGridView


dataGridView1.DataSource = dataTable;
SetupChart();
}

private void timer1_Tick(object sender, EventArgs e)


{
getTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
}

private void btOpen_Click(object sender, EventArgs e)


{
try
{
// Lấy địa chỉ IP của máy
string strHostName = Dns.GetHostName();
IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);

foreach (IPAddress ipAddress in ipHostEntry.AddressList)


{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork) //
Lọc IPv4
{
lanip.Text = ipAddress.ToString();
break; // Lấy địa chỉ IP đầu tiên tìm thấy
}
}

// Kiểm tra cổng


try
{
portServer = int.Parse(t_port.Text);
}
catch
{
MessageBox.Show("Cổng không hợp lệ!", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

startServer = true;

// Kiểm tra giao thức được chọn trong ComboBox


if (comboBox1.SelectedItem.ToString() == "TCP")
{
IPEndPoint iep = new IPEndPoint(IPAddress.Any, portServer);
Serversock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

if (IsPortInUse(portServer))
{
MessageBox.Show("Port " + portServer + " is already in
use.");
return;
}

Serversock.Bind(iep);
Serversock.Listen(1);
MessageBox.Show("Server TCP đã mở thành công!", "Thông báo");
}
else if (comboBox1.SelectedItem.ToString() == "UDP")
{
serversock = new UdpClient(portServer);
remoteEP = new IPEndPoint(IPAddress.Any, portServer);
MessageBox.Show("Server UDP đã mở thành công!", "Thông báo");
}
else
{
MessageBox.Show("Vui lòng chọn giao thức TCP hoặc UDP!", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

// Khởi động luồng lắng nghe client


Thread thClient = new Thread(acceptClient);
thClient.IsBackground = true; // Đảm bảo thread dừng khi ứng dụng
đóng
thClient.Start();
}
catch (Exception ex)
{
MessageBox.Show("Lỗi khi khởi động server: " + ex.Message, "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void btClose_Click(object sender, EventArgs e)


{
if (serversock != null)
{
serversock.Close();
serversock = null; // Giải phóng tài nguyên, tránh lỗi khi mở lại
server
}

startServer = false;

// Xóa thông tin hiển thị trên giao diện


ipc.Invoke((MethodInvoker)delegate { ipc.Text = ""; });
getData.Invoke((MethodInvoker)delegate { getData.Text = ""; });
}

private void btSend_Click(object sender, EventArgs e)


{
string dataSend = string.IsNullOrEmpty(tbSend.Text) ? "Test theo UDP
default" : tbSend.Text;
byte[] command = Encoding.UTF8.GetBytes(dataSend);

if (comboBox1.SelectedItem.ToString() == "TCP") // Gửi bằng TCP


{
if (Clientsock != null && Clientsock.Connected)
{
Clientsock.Send(command, SocketFlags.None);
}
else
{
MessageBox.Show("Client đã ngắt kết nối hoặc chưa kết nối.");
}
}
else if (comboBox1.SelectedItem.ToString() == "UDP") // Gửi bằng UDP
{
if (remoteEP != null)
{
using (UdpClient udpClient = new UdpClient()) // Tạo UDP client
tạm thời
{
udpClient.Send(command, command.Length, remoteEP);
}
}
else
{
MessageBox.Show("Chưa nhận được client nào.");
}
}
else
{
MessageBox.Show("Vui lòng chọn giao thức (TCP hoặc UDP).");
}
}

private void btSave_Click(object sender, EventArgs e)


{
string strIPclient = ipc.Text;
string[] parts = strIPclient.Split(':');
string ipClient = parts[0];
int portClient = int.Parse(parts[1]);
remoteEP = new IPEndPoint(IPAddress.Parse(ipClient), portClient);
SaveDataToDatabase();
}

private void ParseAndDisplayData(string data)


{
try
{
string pattern = @"@(\d+)#(\d+)t";
Match match = Regex.Match(data, pattern);

if (match.Success)
{
float tempValue = float.Parse(match.Groups[1].Value);
float lightValue = float.Parse(match.Groups[2].Value);
string currentTime = DateTime.Now.ToString("yyyy-MM-dd
HH:mm:ss.fff");

if (tb_temp.InvokeRequired)
{
tb_temp.Invoke((MethodInvoker)delegate
{
tb_temp.Text = tempValue.ToString();
tb_light.Text = lightValue.ToString();
dataTable.Rows.Add(countData++, tempValue, lightValue,
currentTime);
});
}
else
{
tb_temp.Text = tempValue.ToString();
tb_light.Text = lightValue.ToString();
dataGridView1.Rows.Add(countData++, tempValue, lightValue,
currentTime);
}

if (chart1.InvokeRequired)
{
chart1.Invoke((MethodInvoker)delegate
{ UpdateChart(currentTime, tempValue, lightValue); });
}
else
{
UpdateChart(currentTime, tempValue, lightValue);
}
}
else
{
MessageBox.Show("Dữ liệu không đúng định dạng!", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi xử lý dữ liệu: " + ex.Message);
}
}

private void SaveDataToDatabase()


{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
foreach (DataRow row in dataTable.Rows)
{
string query = @"
IF EXISTS (SELECT 1 FROM BTH9 WHERE ID = @ID)
UPDATE BTH10
SET Temp = @Temp, Light = @Light, TimeCreat =
@TimeCreat
WHERE ID = @ID
ELSE
INSERT INTO BTH10 (ID, Temp, Light, TimeCreat)
VALUES (@ID, @Temp, @Light, @TimeCreat)";

using (SqlCommand cmd = new SqlCommand(query, conn))


{
cmd.Parameters.AddWithValue("@ID", row["ID"]);
cmd.Parameters.AddWithValue("@Temp", row["Temp"]);
cmd.Parameters.AddWithValue("@Light", row["Light"]);
cmd.Parameters.AddWithValue("@TimeCreat",
row["TimeCreat"]);
cmd.ExecuteNonQuery();
}
}
}
MessageBox.Show("Dữ liệu đã được cập nhật vào CSDL!", "Thông báo",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Lỗi khi lưu dữ liệu: " + ex.Message, "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void SetupChart()


{
chart1.Series.Clear(); // Xóa series cũ

// Tạo series cho nhiệt độ


Series tempSeries = new Series("Nhiệt độ")
{
ChartType = SeriesChartType.Line,
XValueType = ChartValueType.String,
Color = Color.Red
};

// Tạo series cho ánh sáng


Series lightSeries = new Series("Ánh sáng")
{
ChartType = SeriesChartType.Line,
XValueType = ChartValueType.String,
Color = Color.Blue
};

// Thêm series vào chart


chart1.Series.Add(tempSeries);
chart1.Series.Add(lightSeries);

// Tùy chỉnh trục X


chart1.ChartAreas[0].AxisX.LabelStyle.Angle = -45;
chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle =
ChartDashStyle.Dot;

// Tùy chỉnh trục Y


chart1.ChartAreas[0].AxisY.Title = "Giá trị đo";
chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle =
ChartDashStyle.Dot;
}
private void UpdateChart(string time, float temp, float light)
{
// Kiểm tra xem series có tồn tại không
if (chart1.Series.IndexOf("Nhiệt độ") != -1 &&
chart1.Series.IndexOf("Ánh sáng") != -1)
{
chart1.Series["Nhiệt độ"].Points.AddXY(time, temp);
chart1.Series["Ánh sáng"].Points.AddXY(time, light);

// Giới hạn số điểm trên biểu đồ


int maxPoints = 10;
if (chart1.Series["Nhiệt độ"].Points.Count > maxPoints)
{
chart1.Series["Nhiệt độ"].Points.RemoveAt(0);
chart1.Series["Ánh sáng"].Points.RemoveAt(0);
}

// Cập nhật biểu đồ


chart1.ChartAreas[0].RecalculateAxesScale();
}
}

public ParameterizedThreadStart ServerTCP { get; set; }


}
}

You might also like