C# Socket模块
发布日期:2021-06-30 19:37:51
浏览次数:3
分类:技术文章
本文共 2756 字,大约阅读时间需要 9 分钟。
服务端
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Runtime.InteropServices;using System.Net;using System.Net.Sockets;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { //本机IP IPAddress ip = IPAddress.Parse("192.168.0.154"); //IP地址跟端口的组合 IPEndPoint iep = new IPEndPoint(ip, 9000); //创建Socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定Socket socket.Bind(iep); //服务器已经做好接收任何连接的准备 socket.Listen(10); //执行accept方法 Socket Client = socket.Accept(); while (true) { byte[] message = new byte[1024]; NetworkStream networkStream = new NetworkStream(Client); int len = networkStream.Read(message, 0, message.Length); if (len > 0) { byte数组转换成string //string output = System.Text.Encoding.Unicode.GetString(message); //Console.WriteLine("一共从客户端接收了" + len.ToString() + "字节。接收字符串为:" + output); } } } }}
客户端
using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;using System.Threading;using UnityEngine;class ClientNet{ private Socket init() { Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); return clientSocket; } public bool Connect(string host,int port) { if (m_socket == null) m_socket = init(); //要连接的远程IP IPAddress remoteHost = IPAddress.Parse(host); //IP地址跟端口的组合 IPEndPoint iep = new IPEndPoint(remoteHost, port); try { m_socket.Connect(iep); return true; } catch (System.Exception ex) { Debug.LogError("connect error"); return false; } } public void SendData(byte[] bytes) { NetworkStream netstream = new NetworkStream(m_socket); netstream.Write(bytes, 0, bytes.Length); } public void CloseSocket() { m_socket.Shutdown(SocketShutdown.Both); m_socket.Close(); } private Socket m_socket; private static ClientNet s_instance; private static readonly byte[] c_staticLocker = new byte[0]; public static ClientNet Instance { get { if (s_instance == null) { lock (c_staticLocker) { s_instance = new ClientNet(); } } return s_instance; } }}
转载地址:https://linxinfa.blog.csdn.net/article/details/46469107 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月29日 11时48分21秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
synchronized和CAS锁的区别【图文教程】
2019-04-30
配置nginx只允许域名访问,禁止ip访问【图文教程】
2019-04-30
Java代理【图文教程】_第1章_静态代理
2019-04-30
Java代理【图文教程】_第2章_jdk动态代理
2019-04-30
AOP面向切面编程【图文教程】_第1章
2019-04-30
AOP面向切面编程【图文教程】_第2章
2019-04-30
二叉树之前序、中序、后序和层次遍历【图文教程】
2019-04-30
java类的构成
2019-04-30
创建安装linux:centOS
2019-04-30
Xshell连接CentOS及安装hadoop的准备
2019-04-30
在linux上配置jdk和hadoop
2019-04-30
HDFS配置及常见命令
2019-04-30
xshell连接linux速度很慢或者连接一段时间后会自动断
2019-04-30
Hadoop Windows插件配置
2019-04-30