Socket最简单通信代码分享
服务端:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace TcpServer
{
class Program
{
static void Main(string[] args)
{
//确定端口号
int port = 6000;
//设定连接IP
string host = "127.0.0.1";
//将IP地址字符串转化为IP地址实例
IPAddress ip = IPAddress.Parse(host);
//将网络端点表示为 IP 地址和端口号
IPEndPoint ipe = new IPEndPoint(ip, port);
//建立Socket
//addressFamily 参数指定 Socket 类使用的寻址方案
//socketType 参数指定 Socket 类的类型
//protocolType 参数指定 Socket 使用的协议。
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socket与本地终结点建立关联
socket.Bind(ipe);
while (true)
{
//开始监听端口
socket.Listen(0);
Console.WriteLine("服务已开启,请等待....."+ DateTime.Now.ToString());
//为新建的连接建立新的Socket目的为客户端将要建立连接
Socket serverSocket = socket.Accept();
Console.WriteLine("连接已建立......" + DateTime.Now.ToString());
string recStr =string.Empty;
//定义缓冲区用于接收客户端的数据
byte[] recbyte = new byte;
//返回接收到的字节数
int bytes = serverSocket.Receive(recbyte, recbyte.Length, 0);
//将接收到的字节抓获年华为string
//参数一:字节数组 参数二:起始索引 参数三:总长度
recStr += Encoding.ASCII.GetString(recbyte, 0, bytes);
Console.WriteLine("服务器接收到客户端的信息:" + recStr + " " + DateTime.Now.ToString()+"\n\n");
//服务端给客户端回送消息
string strSend = "Hello Client!";
byte[] sendByte = new byte;
//将发送的字符串转换为byte[]
sendByte = Encoding.ASCII.GetBytes(strSend);
//服务端发送数据
serverSocket.Send(sendByte, sendByte.Length, 0);
serverSocket.Close();
}
}
}
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace TcpClient
{
class Program
{
static int port = 6000; //监听端口号
static string host = "127.0.0.1"; //连接服务端IP
static IPAddress ip = IPAddress.Parse(host); //将IP地址转换为IP实例
static IPEndPoint ipe = new IPEndPoint(ip, port);//将网络端点表示为 IP 地址和端口号
static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立客户端Socket
static void Main(string[] args)
{
clientSocket.Connect(ipe); //客户端开始连接服务端
string sendStr = "Hello,Server!"; //向服务器发送消息
byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
clientSocket.Send(sendBytes);
string revStr = ""; //接收来自服务器的消息
byte[] revBytes = new byte;
int bytes = clientSocket.Receive(revBytes, revBytes.Length, 0);
revStr += Encoding.ASCII.GetString(revBytes, 0, bytes);
Console.WriteLine("来自服务端的回应:{0}",revStr);
clientSocket.Close();
}
}
}
转载博客园,未经测试。
页:
[1]