C#实现服务端和客户端交互

来源:转载

需要建两个工程 、一个客户端、一个服务端、


服务端代码:


using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Collections;//服务端测试代码
namespace SimpleServer
{
class Program
{
static void Main(string[] args)
{
IpType();
}
private static void IpType()
{
//IP地址
IPAddress ipaddr = IPAddress.Parse("127.0.0.1");
IPEndPoint endPoint = new IPEndPoint(ipaddr, 33678);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定连接,一定要在监听之前
socket.Bind(endPoint);
//开始监听,最大支持同时5个连接
socket.Listen(5);
while(true)
{
//如果未检测到连接,将阻塞,不再继续执行
Socket clientSocket = socket.Accept();
byte[] data = new byte[512];
//第一次握手,接收到数据确认链接成功
clientSocket.Receive(data, 0, data.Length, SocketFlags.Partial);
string s = System.Text.Encoding.Default.GetString(data);
Console.WriteLine(s.Split('/0')[0]);
//启动新线程处理客户端的连接信息
Task.Factory.StartNew(() =>
{
reciiveFromClient(clientSocket);
});
}
} private static void reciiveFromClient(Socket client)
{
byte[] data;
try
{
while (true)
{
//第二次握手,告诉客户端,服务端已准备好
client.Send(System.Text.Encoding.Default.GetBytes("GoOn"));
data = new byte[512];
//第三次握手,接受数据
client.Receive(data, SocketFlags.None);
string str = System.Text.Encoding.Default.GetString(data);
if (str.StartsWith("_quit"))
{
//如果检测到_quit,关闭连接
client.Close();
Console.WriteLine("连接关闭");
break;
}
else
{
//控制台打印数据
string info = str.Split('/0')[0];
Console.WriteLine("From Client :" + info);
}
}
} catch(SocketException e){
//处理异常
}
}
}
}


客户端代码:


using System;
using System.Net;
using System.Net.Sockets;
//客户端测试代码
namespace SimpleClient
{
class Program
{
static void Main(string[] args)
{
while(true)
{
Client();
//关闭连接后可提示继续连接
Console.WriteLine("End Client");
Console.WriteLine("是否继续?是[Y]/否[N]");
string ss = Console.ReadLine();
if(!(ss == "Y" || ss == "y"))
{
break;
}
}
}
private static void Client()
{
String guid = Guid.NewGuid().ToString();//唯一标识
//指定要连接的服务器IP,本机是127.0.0.1
IPAddress ip = IPAddress.Parse("127.0.0.1");
//端口号
EndPoint ep = new IPEndPoint(ip, 33678);
Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp);
//连接到指定主机
client.Connect(ep);
string s = "Hello, Server,我是:"+ guid;
byte[] data = System.Text.Encoding.Default.GetBytes(s);
//第一次握手,告诉服务器我已经连接
client.Send(data, SocketFlags.Partial);
while (true)
{
byte[] dataReturn = new byte[512];
//第二次握手,确认服务端已准备好
client.Receive(dataReturn, 0, data.Length, SocketFlags.Partial);
Console.WriteLine("From Server:" + System.Text.Encoding.Default.GetString(dataReturn));
//第三次握手,从键盘读取数据
string info = Console.ReadLine();
//转换数据类型
data = System.Text.Encoding.Default.GetBytes(info);
//传输数据到服务器
client.Send(data);
if (info.StartsWith("_quit"))
{
break;
}
}
//关闭连接
client.Close();
}
}
}


分享给朋友:
您可能感兴趣的文章:
随机阅读: