最简单的C#socket通信
来源:互联网 发布:阿里云建ss 编辑:程序博客网 时间:2024/06/06 15:45
服务器端
using System;using System.Collections.Generic;using System.Net;using System.Net.Sockets;namespace SimpleServer{ class Program { static void Main(string[] args) { // 服务器ip地址 string ip = "127.0.0.1"; // 服务器端口 int port = 8000; try { // 获得终端 IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port); // 创建Socket Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 将Socket绑定到终端地址上 listener.Bind(ipe); // 开始监听 最大允许处理1000个连接 listener.Listen(1000); Console.WriteLine("开始监听"); // 开始接受客户端请求 程序在这里会卡阻住 Socket mySocket=listener.Accept(); byte[] bs = new byte[1024]; int n = mySocket.Receive(bs); // 将客户端发来的数据返回给客户端 mySocket.Send(bs); // 半闭与客户端的连接 mySocket.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } } }}
客户端
using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;namespace SimpleClient{ class Program { static void Main(string[] args) { // 服务器ip地址 string ip = "127.0.0.1"; // 服务器端口 int port = 8000; try { // 获得终端 IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port); // 创建Socket Socket client = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // 开始连接服务器,程序在这里会阻住,直接连接成功或失败 client.Connect(ipe); Console.WriteLine("连接到服务器"); //向服务器发送数据 string data = "hello,world"; byte[] bs=UTF8Encoding.UTF8.GetBytes(data); client.Send(bs); // 接收到服务器的数据 byte[] rev = new byte[256]; // 接收到服务器返回的数据 client.Receive(rev); Console.WriteLine(UTF8Encoding.UTF8.GetString(rev)); // 关闭连接 client.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } } }}
0 0
- C/S最简单的socket通信
- 最简单的C#socket通信
- socket通信之最简单的socket通信
- socket通信之最简单的socket通信
- 一个最简单的Socket通信例子
- 一个最简单的Socket通信例子
- 一个最简单的Socket通信例子
- 最简单的Socket通信功能
- 最简单的socket通信 为啥不行?
- C#版 Socket编程(最简单的Socket通信功能
- c++ Windows Socket实现最简单的C/S网络通信(TCP)
- Socket通信最简单实例
- C#:简单的Socket异步通信服务
- 最简单的socket c/s模型
- 一个最简单的socket通信的例子
- Flex 与 C# socket 通信(最简单的例子)
- socket通信之最简单的I/O 多路复用
- socket通信之最简单的I/O 多路复用
- Android Studio使用记录
- 自定义控件H之——聊天ListView
- Hadoop 2.5.2 安装
- 关于android系统编译
- Android开发 图片轮播条Lanner(可无限滚动循环,自定义dots样式位置,延迟时间,滚动时间,点击事件)
- 最简单的C#socket通信
- 递归和闭包的理解
- 了解c#中的三层架构(DAL,BLL,UI)
- memcached主从复制
- 222. Count Complete Tree Nodes
- cmandroid系统编译
- 使用VisualSVN Server和TortoiseSVN 搭建SVN服务器
- RecyclerView 适配器跳过布局问题
- 测试流程