当前位置 : 主页 > 网络编程 > net编程 >

C# Socket模块

来源:互联网 收集:自由互联 发布时间:2023-09-07
服务端 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

服务端

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


网友评论