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

 更新时间:2014年08月06日 10:44:58   投稿:junjie  
这篇文章主要介绍了C#实现的Socket服务器端、客户端代码分享,2个非常简单的入门例子,需要的朋友可以参考下

服务端:

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;
        }
    }
  }
}

相关文章

  • C#数值转换-隐式数值转换表参考

    C#数值转换-隐式数值转换表参考

    隐式转换就是直接使用,比如可以把一个 byte 类型直接用在 int 上
    2013-04-04
  • .NET MemoryCache如何清除全部缓存

    .NET MemoryCache如何清除全部缓存

    本文主要介绍了.NET MemoryCache如何清除全部缓存,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • C#中Thread(线程)和Task(任务)实例详解

    C#中Thread(线程)和Task(任务)实例详解

    .NET Framework在System.Threading命名空间中具有与线程相关的类,线程是一小组可执行指令,这篇文章主要给大家介绍了关于C#中Thread(线程)和Task(任务)的相关资料,需要的朋友可以参考下
    2022-03-03
  • C#中查找Dictionary中的重复值的方法

    C#中查找Dictionary中的重复值的方法

    这篇文章主要介绍了C#中查找Dictionary中的重复值的方法,需要的朋友可以参考下
    2015-09-09
  • C# params可变参数的使用注意详析

    C# params可变参数的使用注意详析

    这篇文章主要给大家介绍了关于C# params可变参数的使用注意的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用C#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-07-07
  • Unity3D使用GL实现图案解锁功能

    Unity3D使用GL实现图案解锁功能

    这篇文章主要为大家详细介绍了Unity3D使用GL实现图案解锁功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-03-03
  • 基于WPF实现弹幕效果的示例代码

    基于WPF实现弹幕效果的示例代码

    这篇文章主要为大家详细介绍了如何利用WPF实现弹幕效果,文中的示例代码讲解详细,对我们学习或工作有一定帮助,感兴趣的小伙伴可以了解一下
    2022-09-09
  • C#实现路由器断开连接,更改公网ip的实例代码

    C#实现路由器断开连接,更改公网ip的实例代码

    C#实现路由器断开连接,更改公网ip的实例代码,需要的朋友可以参考一下
    2013-05-05
  • 一文搞懂c# await,async执行流

    一文搞懂c# await,async执行流

    这篇文章主要介绍了c# await,async执行流的相关知识,文章讲解的非常细致,代码帮助理解和学习,感兴趣的朋友可以了解下
    2020-06-06
  • C#内置队列类Queue用法实例

    C#内置队列类Queue用法实例

    这篇文章主要介绍了C#内置队列类Queue用法,实例分析了C#内置队列的添加、移除等相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-04-04

最新评论