111,123
社区成员
发帖
与我相关
我的任务
分享
public class Server
{
static string data = "";
static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(Listen);
Thread t = new Thread(ts);
t.Start();
}
public static void Listen()
{
IPEndPoint localpoint = new IPEndPoint(IPAddress.Any, 90);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localpoint);
listener.Listen(100);
byte[] bytes;
Socket handler;
int bytesRec;
while (true)
{
Console.WriteLine("waiting for a connection ****");
handler = listener.Accept();
data = "";
while (true)
{
bytes = new byte[1024];
bytesRec = handler.Receive(bytes);
Console.WriteLine("数据是:" + bytesRec.ToString());
data = Encoding.Unicode.GetString(bytes, 0, bytesRec);
Console.WriteLine(data);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
}
class Client
{
static void Main(string[] args)
{
IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint point = new IPEndPoint(address, 90);
Socket sc;
string data;
int bsent;
byte[] b;
sc = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);
sc.Connect(point);
Console.Write("输入:");
while (true)
{
data = Console.ReadLine();
if (data == "exit")
{
sc.Shutdown(SocketShutdown.Both);
sc.Close();
return;
}
b = Encoding.Unicode.GetBytes(data);
bsent = sc.Send(b);
Console.WriteLine(Encoding.Unicode.GetString(b, 0, b.Length) + " has senden");
Console.Write("输入:");
}
}
}