首页 > 代码库 > Socket的简单例子
Socket的简单例子
服务器端
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;//Socket相关的类namespace ChatServer{class Program{static void Main(string[] args){//创建服务器上的监听Socket对象,用来监听客户端的连接请求Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//公开一个IP地址和端口号(终结点EndPoint)IPEndPoint ep = new IPEndPoint(IPAddress.Any, 18888);//将监听Socket对象绑定到终结点server.Bind(ep); //开始监听,100指排队的队列长度server.Listen(100);Console.WriteLine("服务器已经启动了......");//如果有客户端的连接请求,则接收该连接,自动启动一个数据收发的Socekt对象Socket socket = server.Accept();//接收数据byte[] buffer = new byte[1024];int length = socket.Receive(buffer);Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer, 0, length));string info = string.Format("At {0} Server Recive {1} byte info",DateTime.Now.ToString(),length);socket.Send(System.Text.Encoding.UTF8.GetBytes(info));}}}
客户端
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;namespace ChatClient{class Program{static void Main(string[] args){Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Connect连接 的终结点是服务器公开的终结点client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),18888));Console.WriteLine("连接成功了");string info = "hello,I am mwh";//发送数据client.Send(System.Text.Encoding.UTF8.GetBytes(info));byte[] buffer = new byte[1024];int length = client.Receive(buffer);Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer, 0, length));}}}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。