C# Socket TCP Server & Client & nodejs client

要调试公司某项目里的一个功能,因为要准备测试环境,趁这个机会重温了一下Socket(全还给老师了 -_-#),做个备份。

C# Server

        static void Main(string[] args)
{
int port = 81;
string host = "192.168.1.151"; //创建终结点
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port); //创建Socket并开始监听 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建一个Socket对象,如果用UDP协议,则要用SocketTyype.Dgram类型的套接字
s.Bind(ipe); //绑定EndPoint对象(2000端口和ip地址)
s.Listen(0); //开始监听 Console.WriteLine("等待客户端连接"); while (true)
{
//接受到Client连接,为此连接建立新的Socket,并接受消息
Socket temp = s.Accept(); //为新建立的连接创建新的Socket
Console.WriteLine("建立连接");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0); //从客户端接受消息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); //给Client端返回信息
Console.WriteLine("server get message:{0}", recvStr); //把客户端传来的信息显示出来
string sendStr = "server receive message successful!";
byte[] bs = Encoding.UTF8.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0); //返回信息给客户端
temp.Close();
} s.Close();
Console.ReadLine();
Console.Read();
}

C# Client

        static void Main(string[] args)
{
int port = 81;
string host = "192.168.1.151";
//创建终结点EndPoint
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和端口转化为IPEndPoint的实例 //向服务器发送信息
string sendStr = string.Empty; while (true)
{
Console.WriteLine("请输入要发送的内容...");
sendStr = Console.ReadLine();
if (string.IsNullOrWhiteSpace(sendStr))
{
Environment.Exit(0);
}
else
{
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 创建Socket
c.Connect(ipe); //连接到服务器
byte[] bs = Encoding.UTF8.GetBytes(sendStr); //把字符串编码为字节 Console.WriteLine("Send message");
c.Send(bs, bs.Length, 0); //发送信息 //接受从服务器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, 0); //从服务器端接受返回信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
Console.WriteLine("client get message:{0}", recvStr); //回显服务器的返回信息
c.Disconnect(true);
//一定记着用完Socket后要关闭
c.Close();
}
}
}

nodejs client

var net = require('net');
var client = new net.Socket();
//client.setEncoding("utf8");
client.on('data', function(data) {
console.log('DATA: ' + data);
}); client.on('error', function(err) {
console.log('ERROR: ' + err);
}); client.on('end', function(data) {
console.log('END: ' + data);
}); client.connect('81', '192.168.1.151', function () {
console.log('connection success')
}) var msg = "absdfsf中文";
client.write(msg, "utf8", function(){
console.log('send success....')
})
上一篇:[Linux] deepin与nginx


下一篇:dataguard 日志传输服务