基本信息
源码名称:客户端服务器端 tcp socket通信实例源码
源码大小:1.58KB
文件格式:.rar
开发语言:C#
更新时间:2014-07-07
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class server
{
public static void Main()
{
try
{
// 把IP地址转换为IPAddress的实例
IPAddress ipa = IPAddress.Parse("127.0.0.1");
// 初始化监听器, 端口为8001
TcpListener myLsn=new TcpListener(ipa,8001);
// 开始监听服务器端口
myLsn.Start();
// 输出服务器启动信息
Console.WriteLine("在8001端口启动服务...");
Console.WriteLine("本地节点为:" myLsn.LocalEndpoint );
Console.WriteLine("等待连接.....");
// 等待处理接入连接请求
Socket mySock=myLsn.AcceptSocket();
Console.WriteLine("连接来自 " mySock.RemoteEndPoint);
// 接收客户端信息
byte[] data=new byte[100];
int recv=mySock.Receive(data);
Console.WriteLine("已接收...");
for (int i=0;i<recv;i )
{
Console.Write(Convert.ToChar(data[i]));
}
// 处理客户端请求,给客户端回应
ASCIIEncoding asen=new ASCIIEncoding();
mySock.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\n已发送回应信息");
// 善后工作,释放资源
mySock.Close();
myLsn.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " e.StackTrace);
}
}
}