Socket单次连接

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TCP客户端
{
class Program
{
static void Main(string[] args)
{
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddress = IPAddress.Parse(“192.168.2.102”);//可以把一个字符串的IP地址转化成一个ipaddress的对象
EndPoint point = new IPEndPoint(ipaddress, 7788);
tcpClient.Connect(point);//通过IP:端口号定位一个要连接到的服务器端
byte[] data = new byte[1024];
int length = tcpClient.Receive(data);
string message = Encoding.UTF8.GetString(data,0,length);//只把接收到的数据做一个转化 转化为字符串
Console.WriteLine(message);
//向服务器发送消息
string message2 = Console.ReadLine();
tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串转化为字节数组,然后发送到服务器端

        Console.ReadKey();
    }
}

}

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tcp服务端
{
class Program
{
static void Main(string[] args)
{
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建socket
//tcpServer.Bind(new IPEndPoint(IPAddress.Parse(“192.168.2.102”), 7788));//绑定IP -----------简写方法
//绑定IP跟端口号
IPAddress ipaddress = new IPAddress(new byte[] { 192, 168, 2, 102 });
EndPoint point = new IPEndPoint(ipaddress, 7788);//ipendpoint 是对ip + 端口号做了一层封装的类
tcpServer.Bind(point);
tcpServer.Listen(100);//开始监听(等待客户端连接) 最大连接100个客户端
Console.WriteLine(“开始监听”);
Socket clientsocket = tcpServer.Accept();//暂停当前线程,直到有一个客户端链接过来,之后进行下面的代码 返回值是Socket类型
//使用返回的socket跟客户端做通信
Console.WriteLine(“客户端已连接”);
string message = “hello 欢迎使用服务器”;
byte[] data = Encoding.UTF8.GetBytes(message);//对字符串做编码 得到一个字符串的字节数组(byte数组)
clientsocket.Send(data);
Console.WriteLine(“向客户端发送了一条数据”);
byte[] data2 = new byte[1024];
int length = clientsocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2, 0, length);
Console.WriteLine(“从客户端接收到了消息”);
Console.WriteLine(message2);
Console.ReadKey();
}
}
}

猜你喜欢

转载自blog.csdn.net/bellainvan/article/details/107113161