using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//添加Socket類
using System.Net;
using System.Net.Sockets;
namespace SockeConsoleServer
{
class Program
{
static void Main(string[] args)
{
int port = 2000;
string host = "127.0.0.1";
//創建終結點 EndPoint
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip,port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建一個socket對象,如果用UDP協議,則要用SocketTyype.Dgarm類型套接字
s.Bind(ipe); //綁定EndPoint對象(2000端口和ip地址)
s.Listen(0); //開始監聽
Console.WriteLine("等待客戶端連接"); //打印輸出
//接受Client連接,爲此連接建立新的Socket,並接受消息
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.ASCII.GetString(recvBytes, 0, bytes);
//給Client端返回消息
Console.WriteLine("server get message:{0}", recvStr); //把客戶端傳來的消息顯示出來
string sendStr = "ok!Client send message successful!";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0); //返回信息給客戶端
temp.Close();
s.Close();
Console.ReadLine();
//用netstat偵聽下端口的使用情況
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//添加用於socket的類
using System.Net;
using System.Net.Sockets;
namespace SocketConsoleClient
{
class Program
{
static void Main(string[] args)
{
try
{
int port = 2000;
string host = "127.0.0.1";
//創建終結點 EndPoint
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和端口轉化爲IPEndPoint的實例
//創建Socket並連接到服務器
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創建socket
Console.WriteLine("Connecting...");
c.Connect(ipe); //連接到服務器
//向服務器發送消息
string sendStr = "Hello,this is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendStr); //把字符串編寫爲字節
Console.WriteLine("Send message"); //打印輸出
c.Send(bs, bs.Length, 0); //發送消息
//接受從服務器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, 0); //從服務器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("client get message:{0}", recvStr); //回顯服務器的返回信息
Console.ReadLine();
//一定記着用完Socket後要關閉
c.Close();
}
catch (ArgumentException e)
{
Console.WriteLine("argumentNullException:{0}",e);//打印輸出
}
catch(SocketException e)
{
Console.WriteLine("SocketException:{0}",e);//打印輸出
}
}
}
}
Socket通信原理
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.