实现一个客户端和一个服务端通信
可以同时收发多条信息
使用C#语言,通过socket进行通信,基于TCP协议
服务端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace testServer
{
class Program
{
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建服务端
EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000);
server.Bind(point);//绑定端口号和IP
server.Listen(10);//开启监听
Console.WriteLine("服务器开启。。。。");
Socket client = server.Accept();//保存连接进来的客户端
client.Send(Encoding.UTF8.GetBytes("你已经进入服务"));//给客户端发送消息,提示客户端连接成功
Thread t1 = new Thread(reciveMsg);
t1.Start(client);//开启线程接收消息
Thread t2 = new Thread(sendMsg);
t2.Start(client);//开启线程发送消息
}
static void reciveMsg(object obj)
{
Socket client = obj as Socket;
while (true)
{
byte[] buffer = new byte[1024];
try
{
int length = client.Receive(buffer);
string res = Encoding.UTF8.GetString(buffer, 0, length);
Console.WriteLine("接收到的消息:" + res);
}
catch (Exception e)
{
IPEndPoint point = client.RemoteEndPoint as IPEndPoint;
Console.WriteLine(point.ToString()+"断开连接。。。");
break;
}
}
}
static void sendMsg(object obj)
{
Socket client = obj as Socket;
while (true)
{
string s = Console.ReadLine();
client.Send(Encoding.UTF8.GetBytes(s));
}
}
}
}
服务端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace testClient
{
class Program
{
static Socket client;
static Thread t1;
static Thread t2;
static bool isLife = false;//标记是否连接到服务器
static void Main(string[] args)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建客户端
client.Connect(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000));//将客户端连接到服务器
isLife = true;
t1 = new Thread(reciveMsg);
t1.Start();//开启线程接收消息
t2 = new Thread(sendMsg);
t2.Start();//开启线程发送消息
//Console.ReadKey();
}
static void reciveMsg()
{
while (isLife)
{
byte[] buffer = new byte[1024];
try{
int length = client.Receive(buffer);
string res = Encoding.UTF8.GetString(buffer, 0, length);
Console.WriteLine("接收到的消息:" + res);
}catch(Exception e){
Console.WriteLine("reciveMsg: End");
break;
}
}
}
static void sendMsg() {
while (isLife)
{
string s = Console.ReadLine();
try {
client.Send(Encoding.UTF8.GetBytes(s));
}catch (Exception e){
Console.WriteLine("sendMsg: End");
break;
}
if(s.Equals("886")){
isLife = false;
client.Close();
}
}
}
}
}
效果图:
资源下载:
http://download.csdn.net/detail/u011484013/9487030