服务端
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();
}
}
}