-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
62 lines (53 loc) · 1.63 KB
/
Program.cs
File metadata and controls
62 lines (53 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Program
{
static void Main()
{
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Thread receiveThread = new Thread(ReceiveMessages);
receiveThread.Start();
while (true)
{
string message = Console.ReadLine();
SendMessage(name + ": " + message);
}
}
private static void ReceiveMessages()
{
TcpClient client = new TcpClient("localhost", 12345);
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + message);
}
Console.WriteLine("Server disconnected");
Environment.Exit(0);
}
private static void SendMessage(string message)
{
// Lưu nội dung chat vào tệp tin
SaveChatToFile(message);
using (TcpClient client = new TcpClient("localhost", 12345))
{
NetworkStream stream = client.GetStream();
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
}
}
private static void SaveChatToFile(string message)
{
string filePath = "chat_log.txt";
// Ghi nội dung chat vào tệp tin
using (StreamWriter writer = File.AppendText(filePath))
{
writer.WriteLine(message);
}
}
}