【发布时间】:2015-01-30 07:00:40
【问题描述】:
我在套接字编程中创建了一个简单的应用程序。我认为这是实现这一目标的简单方法。所以这就是我分享这个的原因。 在这个程序中,您可以创建服务器程序和客户端程序。您还可以从客户端和服务器发送和接收消息。 这是我的代码
服务器程序:-
class Program
{
private const int port = 4532;
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 4532);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for client");
Socket client = socket.Accept();
IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine(" >> Connected with" + clientIP.Address + "at port" + clientIP.Port);
Console.WriteLine(" >> Accept connection from client");
string welcome = "Welcome";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
Console.WriteLine("......");
Console.Read();
}
}
客户程序:-
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4532);
Console.WriteLine("Client Started");
try
{
socket.Connect(ip);
}
catch(SocketException e)
{
Console.WriteLine("Enable to connect");
}
Console.WriteLine("Conneted to server");
byte[] data = new byte[1024];
int receivedata = socket.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, receivedata);
Console.WriteLine(stringdata);
Console.Read();
}
}
【问题讨论】:
标签: sockets websocket socket.io asyncsocket socketexception