C#实现的Socket服务器端、客户端代码分享
程序员文章站
2023-12-18 11:20:28
服务端:
using system;
using system.collections.generic;
using system.net;
using s...
服务端:
using system; using system.collections.generic; using system.net; using system.net.sockets; using system.text; namespace server { class program { static void main(string[] args) { socket server = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); ipendpoint point = new ipendpoint(ipaddress.parse("127.0.0.1"),55555); try { server.bind(point); server.listen(10); //监听本地端口 system.console.writeline("开始监听本地端口:55555"); while (true) { socket sock = server.accept(); byte[] buffer = new byte[1024 * 1024]; int n = sock.receive(buffer); string cmd = encoding.utf8.getstring(buffer, 0, n); string result = execcmd(cmd); byte[] bytes = encoding.utf8.getbytes(result); sock.send(bytes); } } catch (exception ex) { system.console.writeline(ex.message); return; } } //重定向输入输出流,并且用cmd执行命令 private static string execcmd(string cmd) { system.diagnostics.process p = new system.diagnostics.process(); p.startinfo = new system.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(); return p.standardoutput.readtoend(); } } }
客户端:
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.net; using system.net.sockets; using system.text; using system.threading; using system.windows.forms; /* * code by iswin */ namespace client { public partial class main : form { public main() { initializecomponent(); this.ip.text="127.0.0.1"; this.cmd.text="ipconfig"; this.port.text = "55555"; } private void send_click(object sender, eventargs e) { socket client = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); string remoteip=this.ip.text; string command = this.cmd.text; ipaddress ip = ipaddress.parse(remoteip); ipendpoint point=new ipendpoint(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 (exception ex) { this.recvmsg.text = ex.message; messagebox.show(ex.message); return; } } //接受服务端发送来的消息 private void recvmsgs(socket client) { try { byte[] buffer = new byte[1024 * 1024]; int size = client.receive(buffer); string recv = encoding.utf8.getstring(buffer, 0, size); this.recvmsg.text = "\n" + recv; } catch (exception ex) { messagebox.show(ex.message); return; } } } }