如何让我的消息显示在我的聊天应用程序的文本框中c#socket programming tcp

时间:2017-03-18 00:23:41

标签: c# sockets tcp chat

我已经完成了几个关于套接字编程的教程,除了这个,我没有让它为我工作。我能够让服务器从不同计算机上的多个客户端接收消息。现在我无法弄清楚如何将消息发布到我的文本框中。我很感激任何帮助,因为我对此很陌生。

这是服务器代码:

namespace server_tutorial
{
class Program
{
    static void Main(string[] args)
    {
        //IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
        IPAddress ip = IPAddress.Parse("555.555.5.55");

        TcpListener server = new TcpListener(ip, 8080);
        TcpClient client = default(TcpClient);

        try
        {
            server.Start();
            Console.WriteLine("Server started...");



        }catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Console.Read();
        }

        while (true)
        {

            client = server.AcceptTcpClient();

            byte[] receivedBuffer = new byte[100];
            NetworkStream stream = client.GetStream();

            stream.Read(receivedBuffer, 0, receivedBuffer.Length);

            StringBuilder msg = new StringBuilder();

            foreach(byte b in receivedBuffer)
            {
                if (b.Equals(00))
                {
                    break;
                }
                else
                    msg.Append(Convert.ToChar(b).ToString());
            }

            Console.WriteLine(msg.ToString());

        }
    }
}

这是客户端代码:

namespace client_tutorial
{
public partial class Form1 : Form
{
    string serverIP = "555.555.5.55";
    int port = 8080;

    public Form1()
    {
        InitializeComponent();

    }

    private void submit_Click(object sender, EventArgs e)
    {
        TcpClient client = new TcpClient(serverIP, port);

        int byteCount = Encoding.ASCII.GetByteCount(message.Text);

        byte[] sendData = new byte[byteCount];

        sendData = Encoding.ASCII.GetBytes(message.Text);

        NetworkStream stream = client.GetStream();

        stream.Write(sendData, 0, sendData.Length);

        stream.Close();
        client.Close();

    }
}

我知道这对某些人来说非常简单,但我会感激任何帮助。

0 个答案:

没有答案