简体   繁体   中英

Trying to create a chat application in Visual Studio 2010

I am a beginner in networking but I have to start with something, so I decided to create a chat app in visual studio 2010 using C# language (winforms).

I googled a lot about that and I've found almost exactly what I needed. I found the following code samples (in C# - console):

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=VS.71).aspx

I want to create that application using TCP protocol (I don't know if there are easier ways to do that, but I understood the basics of TCP when I tried to create that chat in C#.

When I executed the code samples in the links above, they worked! So I tried to adapt those samples at my chat application.

My chat application consists actually of two apps: a server and a client. Both of them have the same GUI (two text boxes, a button and two labels for displaying whether the client is connected to the server).

textBox1 on the server/client app is the one that display the message sent by the client/server app. In the textBox2 on the server/client app the user types a message and then presses the button to send the message to the client/server app.

Let me show you what I've tried until now: This is the server application code.

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.Net;
using System.Net.Sockets;


namespace Server_TCP_WINFORMS
{
    public partial class Form1 : Form
    {
    //Int32 port = 13000;
    IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 13000);
    public Form1()
    {
        InitializeComponent();
        server.Start();
    }

    byte[] bytes = new byte[256];
    String data = null;
    TcpClient client = new TcpClient();


    bool sw = true;
    int data_at_byte_level = 0;

    private void Form1_Load(object sender, EventArgs e)
    {

        try
        {


                label2.Text = "Waiting for an incoming connection...";
                if (!server.Pending())
                {
                    label2.Text = "For moment, there are no connections requests!";
                }
                else
                {

                    client = server.AcceptTcpClient();
                    label2.Text = "Connected!";
                    sw = false;
                }



        }
        catch (SocketException xyz)
        {
            MessageBox.Show("Exception occured!");
        }
        if (sw == false)
        {
            NetworkStream stream = client.GetStream();
            while ((data_at_byte_level = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                data = System.Text.Encoding.ASCII.GetString(bytes);
                textBox1.Text += data;
                data = null;
                bytes = null;

            }

        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        String dataT;
        if (textBox2.Text!=null && sw == false)
        {
            NetworkStream stream = client.GetStream();
            dataT = textBox2.Text;
            byte[] msg = System.Text.Encoding.ASCII.GetBytes(dataT);
            stream.Write(msg, 0, msg.Length);
        }
    }


}

}

And this is the client application code:

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.Net.Sockets;
using System.Net;
namespace Client_TCP_WINFORMS
{
  public partial class Form1 : Form
  {
     TcpClient client = new TcpClient("127.0.0.1", 13000); 

    public Form1()
    {
        InitializeComponent();
        label2.Text = "Conected to the server!";

    }

    private void button1_Click(object sender, EventArgs e)
    {
        NetworkStream stream = client.GetStream();
        if (textBox2.Text != null)
        {
            String data_str = textBox2.Text;
            Byte[] data_byte = System.Text.Encoding.ASCII.GetBytes(data_str);
            stream.Write(data_byte, 0, data_byte.Length);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Byte[] data_byte = new Byte[290];
        int bytes;
        string Data;
        NetworkStream stream = client.GetStream();
        bytes = stream.Read(data_byte, 0, data_byte.Length);
        Data = System.Text.Encoding.ASCII.GetString(data_byte, 0, bytes);
        textBox1.Text += Data;

    }
}
}

I want that those two apps to behave in the following way: I start the server application then I start the client application. When both of them are open, I want them to be already connected (because it's simpler that way, I think).

Then, I want that both of them to be receptive which means that when the server (for example) sends a message to the client, the latter one should receive the message and display it. If the server send another message, the client should receive and display it too. If the user (of the client or the user of the server) presses the send button, the application should send the message from the textBox2 to the other application. How can I do those things in windows forms?

I see in the code samples in console that there is a main loop where the server reads the message from the client. But what if the server wants to send a message too? If the send button is pressed, the event for the button_pressed occurs and then it sends the message, but when it finished sending the message, it goes back to the main loop?

Please excuse my english. I am not a native speaker.

Thank you respectfully.

"When both of them are open, I want them to be already connected (because it's simpler that way, I think)."

For this, you need to use UDP(User Datagram Protocol) rather than TCP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM