What's new

C# Pa help naman po C# in visual studio

PHC_Rubiin

Eternal Poster
Established
Joined
Jan 5, 2018
Posts
592
Reaction
212
Points
331
Age
22
create a simple Chat Application that enables users to send messages from one form to another. You will have to learn some networking libraries in order to accomplish this activity. Your application has the capabilities to work in an offline environment where they can send and receive messages simultaneously using C# windows form application.

You will need to add at least 2 window forms; one form is for the sender and the other is for the receiver, it must be vice versa...

lagi po kasi error mga ginagawa kung codes eh.
Example:
1682246439673.png
 

Attachments

Sure! Here's an example of a simple chat application using C# and Windows Forms:

First, we need to create two forms: one for the sender and one for the receiver.

In the sender form, add a TextBox for the user to type their message, a Button to send the message, and a ListBox to display the conversation history. Here's the code for the sender form:

Code:
public partial class SenderForm : Form
{
    // Declare a TCP client and network stream for sending messages
    TcpClient client;
    NetworkStream ns;

    public SenderForm()
    {
        InitializeComponent();
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        // Get the message from the TextBox
        string message = txtMessage.Text;

        // Convert the message to a byte array and send it through the network stream
        byte[] bytes = Encoding.ASCII.GetBytes(message);
        ns.Write(bytes, 0, bytes.Length);

        // Add the message to the conversation history ListBox
        lstConversation.Items.Add("Me: " + message);

        // Clear the TextBox
        txtMessage.Clear();
    }

    private void SenderForm_Load(object sender, EventArgs e)
    {
        // Connect to the receiver's IP address and port number
        client = new TcpClient("ReceiverIPAddress", 8888);
        ns = client.GetStream();
    }
}

In the receiver form, add a ListBox to display the conversation history and a BackgroundWorker to continuously receive messages in the background. Here's the code for the receiver form:

Code:
public partial class ReceiverForm : Form
{
    // Declare a TCP listener and client for receiving messages
    TcpListener listener;
    TcpClient client;

    public ReceiverForm()
    {
        InitializeComponent();

        // Start the background worker to receive messages
        bgwReceiver.RunWorkerAsync();
    }

    private void bgwReceiver_DoWork(object sender, DoWorkEventArgs e)
    {
        // Start listening for incoming connections on port number 8888
        listener = new TcpListener(IPAddress.Any, 8888);
        listener.Start();

        // Accept the incoming connection and get the network stream
        client = listener.AcceptTcpClient();
        NetworkStream ns = client.GetStream();

        while (true)
        {
            // Check if there is any data available in the network stream
            if (ns.DataAvailable)
            {
                // Read the incoming message and convert it to a string
                byte[] bytes = new byte[client.Available];
                ns.Read(bytes, 0, bytes.Length);
                string message = Encoding.ASCII.GetString(bytes);

                // Add the message to the conversation history ListBox
                lstConversation.Invoke(new MethodInvoker(delegate { lstConversation.Items.Add("Sender: " + message); }));
            }
        }
    }

    private void ReceiverForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        // Clean up the TCP listener and client when the form is closed
        listener.Stop();
        client.Close();
    }
}

To use the chat application, simply run the sender and receiver forms on two different machines with different IP addresses. The sender form should connect to the receiver's IP address and port number using a TCP client, and send messages through the network stream. The receiver form should listen for incoming connections on a specified port number using a TCP listener, and receive messages through the network stream continuously in the background using a BackgroundWorker.
 
To accomplish this task, you will need to use the Socket class in C#. The Socket class provides a way to create, connect, send, and receive data over a network.

Here are the steps to create a simple Chat Application:

Step 1: Create two Windows Forms

Create two Windows Forms; one form is for the sender and the other is for the receiver.

Step 2: Design the Forms

Design the forms by adding controls such as text boxes, buttons, and labels to enable users to enter their messages and send them.

Step 3: Add Code to the Forms

Add code to the forms to create a socket, connect to the server, and send and receive messages. Here's an example of how to create a socket and connect to a server:
using System.Net.Sockets;
using System.Text;

// Create a socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Connect to the server
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint endPoint = new IPEndPoint(ipAddress, 1234);
socket.Connect(endPoint);

Step 4: Send and Receive Messages

Once the socket is connected, you can send and receive messages. Here's an example of how to send a message:

string message = "Hello, world!";
byte[] messageBuffer = Encoding.ASCII.GetBytes(message);
socket.Send(messageBuffer);

To receive a message, you can use the Receive method:
byte[] buffer = new byte[1024];
int bytesRead = socket.Receive(buffer);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);

Step 5: Test the Application

Run the sender and receiver forms and test the application by sending messages from one form to the other.

Note: In order to make the application work in an offline environment where users can send and receive messages simultaneously, you will need to use a peer-to-peer network architecture. This is beyond the scope of this tutorial, but there are many resources available online to help you get started with peer-to-peer networking in C#.
 

Similar threads

Back
Top