Socket客户端

C# Socket 客户端示例
本文介绍了一个使用 C# 实现的简单 Socket 客户端程序示例,该程序通过 TCP 协议与服务器进行双向通信,包括发送和接收数据的功能。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace IClient

{
class Program
{
static void Main(string[] args)
{
int port = Convert.ToInt32(Console.ReadLine());
string host = "10.248.87.202";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
Console.WriteLine("Conneting...");
c.Connect(ipe);
Thread t1 = new Thread(new ParameterizedThreadStart(Send));
Thread t2 = new Thread(new ParameterizedThreadStart(Recive));
t1.Start(c);
t2.Start(c);
Console.ReadLine();
}
public static void Send(object temp)
{
while (true)
{
string sendStr = Console.ReadLine().ToString();
byte[] bs = Encoding.Unicode.GetBytes(sendStr);
((Socket)temp).Send(bs, bs.Length, 0);
}
}

public static void Recive(object temp)
{
while (true)
{
string recvStr = "";
byte[] recvBytes = new byte[1024];
var bytes = ((Socket)temp).Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.Unicode.GetString(recvBytes, 0, bytes);
Console.WriteLine("Client:{0}", recvStr);//把客户端传来的信息显示出来
}
}

public static void Closed(Socket Socket, Socket temp)
{
temp.Close();
Socket.Close();
}

}
}

转载于:https://www.cnblogs.com/fuxuyang/p/7419575.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值