1、 首先打開VS新建兩個控制台應用程序:ConsoleApplication_socketServer和ConsoleApplication_socketClient。
2、 在ConsoleApplication_socketClient中輸入以下代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication_socketClient
{
class Program
{
static Socket clientSocket;
static void Main(string[] args)
{
//將網絡端點表示為IP地址和端口 用於socket偵聽時綁定
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("*.*.*.*"), 3001); //填寫自己電腦的IP或者其他電腦的IP,如果是其他電腦IP的話需將ConsoleApplication_socketServer工程放在對應的電腦上。
clientSocket = new Socket(ipep.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
//將Socket連接到服務器
try
{
clientSocket.Connect(ipep);
String outBufferStr;
Byte[] outBuffer = new Byte[1024];
Byte[] inBuffer = new Byte[1024];
while (true)
{
//發送消息
outBufferStr = Console.ReadLine();
outBuffer = Encoding.ASCII.GetBytes(outBufferStr);
clientSocket.Send(outBuffer, outBuffer.Length, SocketFlags.None);
//接收服務器端信息
clientSocket.Receive(inBuffer, 1024, SocketFlags.None);//如果接收的消息為空 阻塞 當前循環
Console.WriteLine("服務器說:");
Console.WriteLine(Encoding.ASCII.GetString(inBuffer));
}
}
catch
{
Console.WriteLine("服務未開啟!");
Console.ReadLine();
}
}
}
}
3、在ConsoleApplication_socketServer中輸入以下代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication_socketServer
{
class Program
{
static Socket serverSocket;
static Socket clientSocket;
static Thread thread;
static void Main(string[] args)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 3001);
serverSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(ipep);
serverSocket.Listen(10);
while (true)
{
clientSocket = serverSocket.Accept();
thread = new Thread(new ThreadStart(doWork));
thread.Start();
}
}
private static void doWork()
{
Socket s = clientSocket;//客戶端信息
IPEndPoint ipEndPoint = (IPEndPoint)s.RemoteEndPoint;
String address = ipEndPoint.Address.ToString();
String port = ipEndPoint.Port.ToString();
Console.WriteLine(address + ":" + port + " 連接過來了");
Byte[] inBuffer = new Byte[1024];
Byte[] outBuffer = new Byte[1024];
String inBufferStr;
String outBufferStr;
try
{
while (true)
{
s.Receive(inBuffer, 1024, SocketFlags.None);//如果接收的消息為空 阻塞 當前循環
inBufferStr = Encoding.ASCII.GetString(inBuffer);
Console.WriteLine(address + ":" + port + "說:");
Console.WriteLine(inBufferStr);
outBufferStr = Console.ReadLine();
outBuffer = Encoding.ASCII.GetBytes(outBufferStr);
s.Send(outBuffer, outBuffer.Length, SocketFlags.None);
}
}
catch
{
Console.WriteLine("客戶端已關閉!");
}
}
}
}
4、先運行ConsoleApplication_socketServer,後運行ConsoleApplication_socketClient就可以通信了。
5、時間有限,希望大家都以上代碼進行優化,因為其中存在不足:比如發言的順序之類的
作者 liyongquanlongliang