C# 服务器及客户端的简单交互

2024-11-22 15:09:22
推荐回答(3个)
回答1:

帖个以前做过的简单代码,写的不好,不过大概原理应该是这样,希望有用。
服务器代码
public partial class ServerMain : Form
{
private IPEndPoint ServerInfo;//存放服务器的IP和端口信息
private Socket ServerSocket;//服务端运行的SOCKET
//private Socket ChildSocket=null;
private Thread ServerThread;//服务端运行的线程
private Socket[] ClientSocket;//为客户端建立的SOCKET连接
private int ClientNumb;//存放客户端数量
private byte[] MsgBuffer;//接受客户发的信息(字节)
string msg;//接受客户发的信息(字符串)
SqlSearch search=new SqlSearch();
private byte[] Mybuffer;
byte[] MYuserName=null;//保存从数据库获取的客户名单(字节)
public ServerMain()
{
InitializeComponent();
}

private void ServerMain_Load(object sender, EventArgs e)
{
this.CmdStart.Enabled = true;
this.CmdStop.Enabled = false;
}

private void CmdStart_Click(object sender, EventArgs e)
{
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerInfo=new IPEndPoint(IPAddress.Any,6666);//this.GetPort());
ServerSocket.Bind(ServerInfo);//将SOCKET接口和IP端口绑定
ServerSocket.Listen(10);//开始监听,并且挂起数为10

ClientSocket = new Socket[1000];//为客户端提供连接个数
MsgBuffer = new byte[5000*5000];//消息数据大小
ClientNumb = 0;//数量从0开始统计

ServerThread = new Thread(RecieveAccept);//将接受客户端连接的方法委托给线程
ServerThread.IsBackground = true;
ServerThread.Start();//线程开始运行

//CheckForIllegalCrossThreadCalls = false;//不捕获对错误线程的调用

this.CmdStart.Enabled = false;
this.CmdStop.Enabled = true;
this.StateMsg.Text = "服务正在运行" + " 运行端口:" + "6666";// this.GetPort().ToString();
this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 开始运行.");
}

private void RecieveAccept()
{
while (true)
{
ClientSocket[ClientNumb] = ServerSocket.Accept();

ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), ClientSocket[ClientNumb]);

this.ClientList.Items.Add(ClientSocket[ClientNumb].RemoteEndPoint.ToString() + " 成功连接服务器.");
ClientNumb++;
}
}
private void RecieveCallBack(IAsyncResult AR)
{
try
{
Socket RSocket = (Socket)AR.AsyncState;
int REnd = RSocket.EndReceive(AR);
for (int i = 0; i < ClientNumb; i++)
{
if (ClientSocket[i].Connected)
{
//ClientSocket[i].Send(MsgBuffer, 0, REnd, 0);

msg = Encoding.Unicode.GetString(MsgBuffer, 0, REnd); //1024 200 + ')
msg = msg.Substring(0,4);

if (msg == "name")//注册判断******************************

if (msg == "User")//判断发送的信息
{
msg = Encoding.Unicode.GetString(MsgBuffer,0,REnd);
string[] recMsg= msg.Split('|');

string Myname = recMsg[1];
string[] name = search.Name();
string friendString = "";
for (int k = 0; k < name.Length; k++)
{
friendString += name[k] + "|";//把好友放在Friend中
}
string[] EachName=friendString.Split('|');
for (int j = 0; j < EachName.Length; j++)
{

if (Myname.Equals(EachName[j]))
{

Mybuffer = Encoding.Unicode.GetBytes(msg);

}
}

ClientSocket[i].Send(Mybuffer, 0, Mybuffer.Length, SocketFlags.None);
}

}
RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);

}
}
catch { }
}

private void CmdStop_Click(object sender, EventArgs e)
{
ServerThread.Abort();//线程终止
ServerSocket.Close();//关闭SOCKET

this.CmdStart.Enabled = true;
this.CmdStop.Enabled = false;
this.StateMsg.Text = "等待运行";
this.ClientList.Items.Add("服务于 " + DateTime.Now.ToString() + " 停止运行.");
}

private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = "当前时间为: "+DateTime.Now.ToString();
label2.Text = "在线人数: " + ClientNumb;
}
}
}

客户端:
public partial class Online : Form
{
private IPEndPoint ServerInfo;
private Socket ClientSocket;
Friend friend = new Friend();
string id, password,msg;
byte[] sendinfo;
byte[] buffer=new byte[1024];

public Online()
{
InitializeComponent();
}

private void btnEnter_Click(object sender, EventArgs e)
{
ServerInfo = new IPEndPoint(IPAddress.Parse("192.168.1.121"), 6666);

try
{

ClientSocket.Connect(ServerInfo);
//MessageBox.Show("登录服务器成功!\n");
id = textID.Text;
password = TextPassWord.Text;
msg = "info"+" "+ id+" " + password;//加消息头info
sendinfo = Encoding.Unicode.GetBytes(msg);
ClientSocket.Send(sendinfo);//获取登录信息并发给服务器

ClientSocket.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);//接受服务器发来的登录信息

//this.btnEnter.Enabled = false;
}
catch
{
MessageBox.Show("登录服务器失败,请确认服务器是否正常工作!");
}
}

private void ReceiveCallBack(IAsyncResult AR)
{
try
{
int REnd = ClientSocket.EndReceive(AR);
string recMsg = Encoding.Unicode.GetString(buffer, 0, REnd);
string cmd = recMsg.Substring(0, 2);
if (cmd == "ok")//根据服务器发来信息判断是否登录成功
{
this.Visible = false;
friend.ShowDialog();
}
if(cmd=="fl")
{
MessageBox.Show("密码有误!登录失败!");
}
ClientSocket.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
catch
{
MessageBox.Show("!");
}

}

private void register_Load(object sender, EventArgs e)
{
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
CheckForIllegalCrossThreadCalls = false;

}

private void linkRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Register reg = new Register();
reg.Show();
}

回答2:

你也说了简单通信。但是要看是很么级别的啊。
一般传递指令 用webservice要跟好些。他速度更快。耗时小。功能也能够实现。
socket 呢。就比较繁琐。我觉得socket要慢。因为你要和服务器连接。然后才能开始socket通信
执行效率低

回答3:

remoting/wcf轻松解决