how-to-make-a-chat-application-in-C-Sharp


SUBMITTED BY: menamagice

DATE: Aug. 9, 2017, 1:55 a.m.

FORMAT: ANTLR With C# Target

SIZE: 5.1 kB

HITS: 216

  1. This project shows you how to make a chat application step-by-step in Microsoft Visual C#. This project uses a UDP (User Datagram Protocol) Socket connection between two chat applications. This chat application can work within the same network or across networks.
  2. However, in this project, I shall be focusing on how to communicate asynchronously with two chat applications. An Asynchronous Communication system is a way of communicating where both sides can communicate simultaneously with each other. For example, a telephone call is an example of asynchronous communication system.
  3. I am going to show you step-by-step skipping no step.
  4. Step 1: First make a project, go to Microsoft Visual C# then create a project.
  5. Step 2: Design the Chat Application form with TextBox, label, button and group boxes.
  6. Give the form objects names as in the following:
  7. Your IP textbox name = textLocalIp,
  8. Your Port textbox name = textLocalPort,
  9. Friend's IP textbox name = textFriendsIp
  10. Friend's Port textbox name = textFriendsPort
  11. Listbox Message name = listMessage,
  12. Textbox for Message sending name = textMessage,
  13. Start Button name = buttonStart,
  14. Send Button name = buttonSend
  15. Step 3: Add 2 namespaces to the project.
  16. using System.Net;
  17. using System.Net.Sockets;
  18. Step 4 : Add the following code for the form load, double-click on the form then write the following code.
  19. // set up socket
  20. sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  21. sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  22. // get own IP
  23. textLocalIp.Text = GetLocalIP();
  24. textFriendsIp.Text = GetLocalIP();
  25. Then add a method GetLocalIP() as follows. This method will return the Local IP address to the text boxes.
  26. // Return your own IP
  27. private string GetLocalIP()
  28. {
  29. IPHostEntry host;
  30. host = Dns.GetHostEntry(Dns.GetHostName());
  31. foreach (IPAddress ip in host.AddressList)
  32. {
  33. if (ip.AddressFamily == AddressFamily.InterNetwork)
  34. {
  35. return ip.ToString();
  36. }
  37. }
  38. return "127.0.0.1";
  39. }
  40. Step 5: Add the following code under the Start Button click event.
  41. try
  42. { // binding socket
  43. epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
  44. sck.Bind(epLocal);
  45. // connect to remote IP and port
  46. epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
  47. sck.Connect(epRemote);
  48. // starts to listen to an specific port
  49. buffer = new byte[1500];
  50. sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new
  51. AsyncCallback(MessageCallBack), buffer);
  52. // release button to send message
  53. buttonSend.Enabled = true;
  54. buttonStart.Text = "Connected";
  55. buttonStart.Enabled = false;
  56. textMessage.Focus();
  57. }
  58. catch (Exception ex)
  59. {
  60. MessageBox.Show(ex.ToString());
  61. }
  62. Now, you need to add a callback function MessageCallBack. Just add the following code.
  63. try
  64. {
  65. int size = sck.EndReceiveFrom(aResult, ref epRemote);
  66. // check if theres actually information if (size > 0) { // used to help us on getting the data
  67. byte[] receivedData = new byte[1464];
  68. // getting the message data
  69. receivedData = (byte[])aResult.AsyncState;
  70. // converts message data byte array to string
  71. ASCIIEncoding eEncoding = new ASCIIEncoding();
  72. string receivedMessage = eEncoding.GetString(receivedData);
  73. // adding Message to the listbox
  74. listMessage.Items.Add("Friend: " + receivedMessage);
  75. }
  76. // starts to listen the socket again
  77. buffer = new byte[1500];
  78. sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
  79. }
  80. catch (Exception exp)
  81. {
  82. MessageBox.Show(exp.ToString());
  83. }
  84. Step 6: In this step you need to add the following code for the send button click event.
  85. try
  86. { // converts from string to byte[]
  87. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  88. byte[] msg = new byte[1500];
  89. msg = enc.GetBytes(textMessage.Text);
  90. // sending the message
  91. sck.Send(msg);
  92. // add to listbox
  93. listMessage.Items.Add("You: " + textMessage.Text);
  94. // clear txtMessage
  95. textMessage.Clear();
  96. }
  97. catch (Exception ex)
  98. {
  99. MessageBox.Show(ex.ToString());
  100. }
  101. Step 7: Now build the project by clicking the Build menu then the Build Solution sub-menu. And now go to the project folder and go inside the project folder to the bin folder then bin debug. In the debug folder you will see the ChatApps.exe file.
  102. Open two instances for testing purposes in your computer, then give a different Port number as you are listening in the same IP. Then connect both Applications and start sending messages. I hope you will enjoy this project. If you want to chat with your friends or colleagues in the LAN or the same network then give them a copy of ChattApps.exe and now you will be able to chat from a different computer.

comments powered by Disqus