C# Socket简单例子(服务器与客户端通信)
2020-12-13 16:39
标签:style http io color ar os sp for 数据 先发服务端的(Server)完整代码如下: 客户端(Client)的完整代码如下: 先运行server端代码,再运行client端代码,结果如下 server:
client:
具体socket知识:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2 这是在控制台中进行server与client之间的通信,下一步是实现server与client之间在窗口的通信 C# Socket简单例子(服务器与客户端通信) 标签:style http io color ar os sp for 数据 原文地址:http://my.oschina.net/zhangxuman/blog/342450using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace SocketServer
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8885; //端口
static Socket serverSocket;
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
serverSocket.Listen(10); //设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketClient
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
//通过clientSocket接收数据
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
//通过 clientSocket 发送数据
for (int i = 0; i