服务端
- 1、创建Socket
- 2、调用Bind绑定IP地址和端口号
- 3、调用Listen等待客户端连接
- 4、调用Accept接受客户端连接
- 5、在While中回应消息并打印客户端发来的消息
using System;
using System.Net;
using System.Net.Sockets;
namespace Serv
{
class Program
{
const int BUFFER_SIZE = 1024;
static byte[] readBuff = new byte[BUFFER_SIZE];
static void Main(string[] args)
{
Console.Write("Hello World!!!\n");
Socket listened = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEp = new IPEndPoint(ipAdr, 1234);
listened.Bind(ipEp);
listened.Listen(0);
Console.WriteLine("Server is starting");
Socket confd = listened.Accept();
Console.WriteLine("server Accept");
while (true)
{
int count = confd.Receive(readBuff);
String str = System.Text.Encoding.Default.GetString(readBuff, 0, count);
Console.WriteLine(str);
str = "Server:Hello Heiren!!!";
byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
confd.Send(bytes);
}
}
}
}
客户端
- 1、创建Socket
- 2、调用Connect连接服务端
- 3、在while中发送信息和打印接受的消息
- 4、当控制台输入exit时,退出循环,关闭连接
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
namespace Client
{
class Program
{
static Socket socket;
const int BUFFER_SIZE = 1024;
static byte[] readBuff = new byte[BUFFER_SIZE];
public static void Main(string[] args)
{
Console.Write("Client Hello World!!!\n");
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Connect("127.0.0.1",1234);
int num = 0;
while(true)
{
String str = "Client:Hello Heiren!!!";
if (num == 0) num++;
else str = Console.ReadLine();
if (str.Equals("exit"))
break;
byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
socket.Send(bytes);
int count = socket.Receive(readBuff);
str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
Console.WriteLine(str);
}
socket.Close();
}
}
}