Socket端口制作简单聊天室

聊天室服务端与客户端通信
本文详细介绍了基于TCP协议的聊天室服务端与客户端之间的通信流程,包括服务器端的监听、绑定、接受连接,以及客户端的连接、接收消息和发送消息的过程。

服务端

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;


namespace 聊天室服务端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.引用名字空间 using System.Net; using System.Net.Sockets;
            //2.创建服务器的端口
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //3.端口号,一个软件占用一个端口号
            int pose = 3000;
            //4.IP地址
            IPAddress ip = IPAddress.Parse("192.168.1.104");
            //5.绑定ip和端口号 EndPoint对ip和端口封装
            EndPoint point = new IPEndPoint(ip, pose);
            //6.绑定,向操作系统申请一个可用的ip和端口来做通信
            tcpServer.Bind(point);
            //7.最大连接数
            tcpServer.Listen(100);
            Console.WriteLine("等待连接...");
            //8.暂停当前线程,直到有一个客户端接过来,之后进行下面的代码
            Socket clientSocket = tcpServer.Accept();
            Console.WriteLine("连接成功");


            //向客户端发送消息
            string message = "欢迎进入聊天室";
            byte[] data = Encoding.Default.GetBytes(message);
            clientSocket.Send(data);


            //接收客户端的消息
            byte[] data2 = new byte[1024];
            int length = clientSocket.Receive(data2);
            string message2 = Encoding.Default.GetString(data2, 0, length);
            Console.WriteLine(message2);


            Console.ReadKey();
        }
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

客户端

namespace 聊天室客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int pose = 3000;
            IPAddress ip = IPAddress.Parse("192.168.1.104");
            EndPoint point = new IPEndPoint(ip, pose);
            //通过ip和端口 定位一个要连接到的服务器端
            tcpClient.Connect(point);


            byte[] data = new byte[1024];
            int length = tcpClient.Receive(data);//返回值表示接收了多少字节的数据
            string message = Encoding.Default.GetString(data, 0, length);
            Console.WriteLine(message);


            //向服务器端发送消息
            string message2 = Console.ReadLine();
            tcpClient.Send(Encoding.Default.GetBytes(message2));


            Console.ReadKey();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值