记C#一次服务器搭建和数据库应用

服务器端

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

 

namespace Servece

{

class Program

{

static void Main(string[] args)

{

//搭建

Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

IPAddress ip = IPAddress.Parse("192.168.1.14");

IPEndPoint ipPoint = new IPEndPoint(ip, 1234);

serverSocket.Bind(ipPoint);//建立连接

serverSocket.Listen(0);//监听

//Socket clientSocket = serverSocket.Accept(); 只能接收一个客户端

serverSocket.BeginAccept(AcceptCall, serverSocket);

Console.ReadKey();//很重要,不然会报错。作用:等待键盘输入,退出程序,使调试时能看到输出结果。如果没有此句,命令窗口会一闪而过。

 

}

static void AcceptCall(IAsyncResult ar) {

 

Socket severSocket = ar.AsyncState as Socket;

//给客户端发送信息

Socket clientSocket =severSocket.EndAccept(ar);

string msg = "你已连上服务器";

byte[] data = Encoding.UTF8.GetBytes(msg);

clientSocket.Send(data);

//接收客户端发来的信息

dataBuffer = new byte[1024];

 

clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReciveClient, clientSocket);

severSocket.BeginAccept(AcceptCall, severSocket);

 

}

static byte[] dataBuffer=new byte[1024];

static void ReciveClient(IAsyncResult ar)

{

Socket clientSocket = null;

//用try来处理客户端突然关闭的情况

try

{

clientSocket = ar.AsyncState as Socket;

 

int count = clientSocket.EndReceive(ar);

//当没有传过来信息的时候,关闭客户端

if (count == 0) {

 

clientSocket.Close();

return;

}

 

string msg = Encoding.UTF8.GetString(dataBuffer, 0, count);

Console.WriteLine("从客户端接收到消息:" + msg);

 

clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReciveClient, clientSocket);

}

catch (Exception e)

{

 

clientSocket.Close();

Console.WriteLine(e);

}

 

}

}

}

 

 

 

 

客户端

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

 

namespace ClientSocket

{

class Program

{

static void Main(string[] args)

{

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

 

//与服务器建立连接

client.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.14"), 1234));

//接收服务器发送的消息

byte[] data = new byte[1024];

int count = client.Receive(data);

string msg = Encoding.UTF8.GetString(data, 0, count);

Console.WriteLine(msg);

while (true)

{

 

string s = Console.ReadLine();

if (s == "q") {//按回车不发送

 

client.Close();

return;

}

client.Send(Encoding.UTF8.GetBytes(s));//给服务器发送

Console.ReadKey();

}

}

}

}

 

 

 

 

 

 

Console.ReadKey()//暂停

运行多个客户端

 

 

 

 

 

 

 

 

 

 

 

粘包解决:

 

服务器端:

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

 

namespace Servece

{

class Program

{

static void Main(string[] args)

{

//搭建服务器

Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPAddress ip = IPAddress.Parse("192.168.1.14");

IPEndPoint ipPoint = new IPEndPoint(ip, 1234);

serverSocket.Bind(ipPoint);//建立连接

serverSocket.Listen(0);//监听

//Socket clientSocket = serverSocket.Accept(); 只能接收一个客户端

serverSocket.BeginAccept(AcceptCall, serverSocket);

Console.ReadKey();//很重要,不然会报错。作用:等待键盘输入,退出程序,使调试时能看到输出结果。如果没有此句,命令窗口会一闪而过。

 

}

static Message ms = new Message();

static void AcceptCall(IAsyncResult ar)

{

 

Socket severSocket = ar.AsyncState as Socket;

//给客户端发送信息

Socket clientSocket = severSocket.EndAccept(ar);

string msgStr = "你已连上服务器";

byte[] data = Encoding.UTF8.GetBytes(msgStr);

clientSocket.Send(data);

 

//异步接收客户端发来的信息

dataBuffer = new byte[1024];

clientSocket.BeginReceive(ms.Data, ms.StartIndex, ms.RemainSize, SocketFlags.None, ReciveClient, clientSocket);

severSocket.BeginAccept(AcceptCall, severSocket);

 

}

static byte[] dataBuffer;

static void ReciveClient(IAsyncResult ar)

{

Socket clientSocket = null;

//用try来处理客户端突然关闭的情况

try

{

clientSocket = ar.AsyncState as Socket;

 

int count = clientSocket.EndReceive(ar);

//当没有传过来信息的时候,关闭客户端

if (count == 0)

{

 

clientSocket.Close();

return;

}

 

ms.AddCount(count);

ms.ReadMessage();

 

clientSocket.BeginReceive(ms.Data, ms.StartIndex, ms.RemainSize, SocketFlags.None, ReciveClient, clientSocket);

 

}

catch (Exception e)

{

 

clientSocket.Close();

Console.WriteLine(e);

}

 

 

}

}

}

 

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Servece

{

class Message

{

private byte[] data = new byte[1024];

private int startIndex;//数组 总长度

 

public byte[] Data

{

get

{

return data;

}

 

set

{

data = value;

}

}

 

public int RemainSize {

 

get { return data.Length - StartIndex; }

}//余空间

 

public int StartIndex

{

get

{

return startIndex;

}

 

set

{

startIndex = value;

}

}

 

public void AddCount(int count) {

 

StartIndex += count;

}

public void ReadMessage() {

 

while (true) {

 

if (StartIndex <= 4) return;

int count = BitConverter.ToInt32(data, 0);//读四位

if (StartIndex - 4 >= count)

{

 

string s = Encoding.UTF8.GetString(data, 4, count);

Console.WriteLine("result is:" + s);

Array.Copy(data, count + 4, data, 0, StartIndex - 4 - count);

StartIndex -= (count + 4);

}

else{

break;

}

}

}

 

}

}

 

 

客户端

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

 

namespace ClientSocket

{

class Program

{

static void Main(string[] args)

{

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.14"), 1234));

 

byte[] data = new byte[1024];

int count = client.Receive(data);

string msg = Encoding.UTF8.GetString(data, 0, count);

Console.WriteLine(msg);

//while (true)

//{

 

// string s = Console.ReadLine();

// if (s == "q") {//按回车不发送

 

// client.Close();

// return;

// }

// client.Send(Encoding.UTF8.GetBytes(s));

// Console.ReadKey();

//}

for (int i = 0; i < 100; i++)

{

//client.Send(Encoding.UTF8.GetBytes(i.ToString()));

client.Send(Message.GetByte(i.ToString()));

 

}

}

}

}

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ClientSocket

{

class Message

{

//粘包的解决办法:将客户端发送给服务器的信息前四位设置成信息的长度,后面是内容。

public static byte[] GetByte(string data) {

//1.接收要发送给服务器的内容,将其转换成字节数组。

//2.记录消息的长度将长度(int)转换成字节数组类型。

//3.新的字节数组将两个数组结合起来。

byte[] dataByte = Encoding.UTF8.GetBytes(data);

int dataLength = dataByte.Length;

byte[] lengthBytes = BitConverter.GetBytes(dataLength);

byte[] newByte = lengthBytes.Concat(dataByte).ToArray();

return newByte;

}

}

}

 

 

 

 

 

 

 

 

丢包了。

 

 

重新运行没丢。

 

 

解决粘包

 

数据库

引入dll文件

 

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using MySql.Data.MySqlClient;

namespace Test4

{

class Program

{

static void Main(string[] args)

{

//本地ip localhost 127.0.0.1

//使用MySqlConnection连接数据库,需要指定 数据库名称 ip 端口 用户名 密码

string connStr="Database=test1;Data Source=127.0.0.1;port=3306;User Id=root;Password=user";

MySqlConnection conn = new MySqlConnection(connStr);//创建连接通道

 

conn.Open();//打开连接

 

// Insert(conn);

 

// Delete(conn);

Update(conn);

Find(conn);

conn.Close();

}

static void Find(MySqlConnection conn)

{

MySqlCommand cmd = new MySqlCommand("select * from user", conn);//使用Mysql命令查询id

 

MySqlDataReader reader = cmd.ExecuteReader();//执行查询

 

while (reader.Read())//判断是否读到了数据

{

//读取一行记录

string username = reader.GetString("username");

string password = reader.GetString("password");

Console.WriteLine(username + "+" + password);

}

reader.Close();

}//查询

static void Insert(MySqlConnection conn)//插入

{

string username = "zhangsan";

string password = "123';delete from user;";

//SQl注入

//MySqlCommand cnd = new MySqlCommand("insert into user set username='"+username+"',password='"+password+"'",conn);

 

MySqlCommand cnd = new MySqlCommand("insert into user set username=@un,password=@pwd",conn);

cnd.Parameters.AddWithValue("un",username);

cnd.Parameters.AddWithValue("pwd", password);

 

cnd.ExecuteNonQuery();//执行和查询无关的语句

}

static void Delete(MySqlConnection conn)//删除

{

MySqlCommand cmd = new MySqlCommand("delete from user where id=@id", conn);

cmd.Parameters.AddWithValue("id", 3);

cmd.ExecuteNonQuery();

}

static void Update(MySqlConnection conn)//更新

{

MySqlCommand cmd = new MySqlCommand("update user set password=@pwd where id=4", conn);

cmd.Parameters.AddWithValue("pwd", "qwer");

 

cmd.ExecuteNonQuery();

}

}

}

 

 

 

 

 

 

 

 

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using MySql.Data.MySqlClient;//引入命名空间

 

namespace Database

{

class Program

{

static void Main(string[] args)

{

string constr = "Database=test;Data Source=127.0.0.1;port=3306;User Id=root;Password=root";

MySqlConnection conn = new MySqlConnection(constr);

conn.Open();

 

MySqlCommand cmd = new MySqlCommand("select * from user", conn);

MySqlDataReader reader=cmd.ExecuteReader();

//reader.HasRows 只执行了一次结果是满足条件的第一条记录

 

if (reader.Read()) {

 

//reader.Read();遍历出所有的结果

string user = reader.GetString("username");

string pass = reader.GetString("userpass");

Console.WriteLine(user+" "+pass);

}

 

 

}

}

}

结果:

 

表:

 

posted @ 2018-02-27 22:01  薛小爽  阅读(461)  评论(0编辑  收藏  举报