Socket客户端

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

}
}

posted @ 2017-08-23 18:26  付旭洋  阅读(201)  评论(0编辑  收藏  举报