C# Console 编程
服务器端:csharpconsolesokecttestserver.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace csharpconsolesokecttestserver
{
class Program
{
static void Main(string[] args)
{
int port = 2000;
string host = "127.0.0.1";
IPAddress ip=IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
s.Bind(ipe);//绑定2000端口
s.Listen(0);//开始监听
Console.WriteLine("等待连接...");
Socket temp=s.Accept();//为新建连接创建新的Socket。
Console.WriteLine("连接成功...");
string recvstr = "";
byte[] recvbytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvbytes, recvbytes.Length, 0);//从客户端接受信息
recvstr += Encoding.UTF8.GetString(recvbytes, 0, bytes);//将byte转换成str,编码用UTF-8
Console.WriteLine("服务器端获取信息为:/n{0}",recvstr);
string sendstr = "服务器已接受来自客户端的信息.";
byte[] bs = Encoding.UTF8.GetBytes(sendstr);
temp.Send(bs,bs.Length,0);
temp.Close();
s.Close();
Console.ReadLine();
}
}
}