简体   繁体   English

尝试在 Visual Studio 2010 中创建聊天应用程序

[英]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).我是网络初学者,但我必须从一些东西开始,所以我决定使用 C# 语言(winforms)在 Visual Studio 2010 中创建一个聊天应用程序。

I googled a lot about that and I've found almost exactly what I needed.我在谷歌上搜索了很多,我几乎找到了我需要的东西。 I found the following code samples (in C# - console):我找到了以下代码示例(在 C# 中 - 控制台):

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx 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 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#.我想使用 TCP 协议创建该应用程序(我不知道是否有更简单的方法来做到这一点,但是当我尝试在 C# 中创建该聊天时,我了解了 TCP 的基础知识。

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).它们都具有相同的 GUI(两个文本框、一个按钮和两个用于显示客户端是否连接到服务器的标签)。

textBox1 on the server/client app is the one that display the message sent by the client/server app.服务器/客户端应用程序上的 textBox1 是显示客户端/服务器应用程序发送的消息的文本框。 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.在服务器/客户端应用程序的 textBox2 中,用户键入一条消息,然后按下按钮将消息发送到客户端/服务器应用程序。

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.如果用户(客户端或服务器用户)按下发送按钮,应用程序应该将消息从 textBox2 发送到另一个应用程序。 How can I do those things in windows forms?我怎样才能在 Windows 窗体中做这些事情?

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?如果按下发送按钮,则 button_pressed 的事件发生,然后它发送消息,但是当它发送完消息时,它返回到主循环?

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为此,您需要使用 UDP(用户数据报协议)而不是 TCP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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