Windows Forms: TCP/IP Client & Server in C#
By FoxLearn 5/22/2017 10:05:29 PM 81.27K
Create a simple chat TCP/IP Client & Server using SimpleTCP library in C#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "TCPIPDemo" and then click OK. Similar with "Client" project
Step 2: Right click on your project select Manage NuGet Packages -> Search simpletcp -> Install
Step 3: Design your form as below
Client
Server
You can change the host and port to connect over the network, connect through the network you should open the firewall to allow connection to your port
Add code to handle client form
namespace Client { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SimpleTcpClient client; private void btnConnect_Click(object sender, EventArgs e) { btnConnect.Enabled = false; //Connect to server client.Connect(txtHost.Text, Convert.ToInt32(txtPort.Text)); } private void Form1_Load(object sender, EventArgs e) { client = new SimpleTcpClient(); client.StringEncoder = Encoding.UTF8; client.DataReceived += Client_DataReceived; } private void Client_DataReceived(object sender, SimpleTCP.Message e) { //Update message to txtStatus txtStatus.Invoke((MethodInvoker)delegate () { txtStatus.Text += e.MessageString; }); } private void btnSend_Click(object sender, EventArgs e) { client.WriteLineAndGetReply(txtMessage.Text, TimeSpan.FromSeconds(3)); } } }
Add code to handle server form
namespace TCPIPDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SimpleTcpServer server; private void Form1_Load(object sender, EventArgs e) { server = new SimpleTcpServer(); server.Delimiter = 0x13;//enter server.StringEncoder = Encoding.UTF8; server.DataReceived += Server_DataReceived; } private void Server_DataReceived(object sender, SimpleTCP.Message e) { //Update mesage to txtStatus txtStatus.Invoke((MethodInvoker)delegate () { txtStatus.Text += e.MessageString; e.ReplyLine(string.Format("You said: {0}", e.MessageString)); }); } private void btnStart_Click(object sender, EventArgs e) { //Start server host txtStatus.Text += "Server starting..."; System.Net.IPAddress ip = System.Net.IPAddress.Parse(txtHost.Text); server.Start(ip, Convert.ToInt32(txtPort.Text)); } private void btnStop_Click(object sender, EventArgs e) { if (server.IsStarted) server.Stop(); } } }
VIDEO TUTORIALS
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
- Windows Forms: Wait Form Dialog in C#
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#