服务器端:
项目一:
Program类:
class Program
{
static void Main(string[] args)
{
ServerTest.getInstance().Listen();
Console.ReadKey();
}
}
Server类:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace YueKaoTest
{
class ServerTest
{
//单例模式
private static ServerTest _instance;
private ServerTest() { }
public static ServerTest getInstance() {
if (_instance == null)
_instance = new ServerTest();
return _instance;
}
Socket server;
List<Socket> clientList = new List<Socket>();
byte[] buffer = new byte[1024];
public void Listen() {
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10087);
server.Bind(endPoint);
server.Listen(10);
Console.WriteLine("服务器启动成功");
//循环接收客户端
while (true)
{
Socket client = server.Accept();
clientList.Add(client);
Console.WriteLine(((IPEndPoint)client.RemoteEndPoint).Address + "已连接");
Thread thread = new Thread(ClientHandel);
thread.Start(client);
}
}
/// <summary>
/// 开启新函数接收数据
/// </summary>
/// <param name="obj"></param>
private void ClientHandel(object obj)
{
Socket client = obj as Socket;
//对同一个客户端不停接收消息
while (true)
{
int len;
try
{
//收到数据的长度
len = client.Receive(buffer);
}
catch (Exception)
{
Console.WriteLine("有一个客户端失去连接!");
client.Close();
clientList.Remove(client);
Thread.CurrentThread.Abort();
break;
}
if (len <= 0)
{
Console.WriteLine("有一个客户端失去连接!");
client.Close();
clientList.Remove(client);
Thread.CurrentThread.Abort();
break;
}
else
{
byte[] dataArr = new byte[len];
Array.Copy(buffer, 0, dataArr, 0, len);
HandleMsg(dataArr, client);
}
}
}
/// <summary>
/// 处理收到的数据
/// </summary>
/// <param name="dataArr"></param>
/// <param name="client"></param>
private void HandleMsg(byte[] dataArr, Socket client)
{
string str = Encoding.UTF8.GetString(dataArr);
string[] msgArr = str.Split('|');
//广播
if (msgArr[0] == "1") {
for (int i = clientList.Count - 1; i >= 0; i--) {
Socket socket = clientList[i];
//将自己排除在广播外
if (socket == client)
continue;
try
{
socket.Send(dataArr);
}
catch (Exception)
{
Console.WriteLine(((IPEndPoint)socket.RemoteEndPoint).Address + "已掉线");
socket.Close();
clientList.RemoveAt(i);
}
}
}
}
}
}
Server类:
项目二(WebAPI):
1.添加引用MySql.Data
2.Model 文件夹放DataBaseMgr,SimpleJson,UserInfo
3.Controllers 文件夹放 xxxController 类 ,xxx自命名
-------------------------DataBaseMgr------------------------
using MySql.Data.MySqlClient;
using System;
namespace MyWebAPI.Models
{
public class DataBaseMsg
{
private string connectStr=
"Persist Security Info=False;database=st001;server=127.0.0.1;user id=root;pwd=123456";
private MySqlConnection conn;
/// <summary>
/// 连接数据库
/// </summary>
public void OpenDB() {
try
{
conn = new MySqlConnection();
conn.ConnectionString = connectStr;
conn.Open();
Console.WriteLine("数据库已打开!");
}
catch (Exception)
{
Console.WriteLine("数据库打开失败!");
conn.Close();
conn = null;
}
}
public bool Add(int id, string UserName, string Password) {
//如果数据库关闭,则从新打开
if (conn == null || conn.State == System.Data.ConnectionState.Closed) {
OpenDB();
}
//SQL语句
string inserSql = "INSERT INTO st001(id,nameuser,password) values('{0}','{1}','{2}')";
inserSql = string.Format(inserSql, id, UserName, Password);
//创建命令
MySqlCommand command = conn.CreateCommand();
//执行指定命令
command.CommandText = inserSql;
//开始执行非查询,返回受影响行数
int num = command.ExecuteNonQuery();
if (num > 0)
{
return true;
}
else {
return false;
}
}
public bool getUser(string UserName, string Password) {
//如果数据库关闭,则从新打开
if (conn == null || conn.State == System.Data.ConnectionState.Closed)
{
OpenDB();
}
string selSql = "SELECT name FROM myuser WHERE NameUser='{0}' AND Password='{1}'";
selSql = string.Format(selSql, UserName, Password);
//创建命令
MySqlCommand command = conn.CreateCommand();
//执行命令
command.CommandText = selSql;
//执行查询
MySqlDataReader reader = command.ExecuteReader();
bool us = false;
while (reader.Read()) {
if (reader.GetString("name") != null)
us = true;
}
reader.Close();
return us;
}
}
}
----------------------------------------UserInfo-------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyWebAPI.Models
{
public class UserInfo
{
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string msg { get; set; }
}
}
===================Controller 文件夹==============
using MyWebAPI.Models;
using System.Web.Http;
namespace MyWebAPI
{
public class TestController : ApiController
{
public UserInfo GetInfo(string str)
{
UserInfo userInfo = SimpleJson.SimpleJson.DeserializeObject<UserInfo>(str);
DataBaseMsg dbm = new DataBaseMsg();
dbm.OpenDB();
if (dbm.getUser(userInfo.username, userInfo.password))
{
userInfo.msg = "登陆成功";
}
else
{
userInfo.msg = "账号或密码错误";
}
return userInfo;
}
//public string GetUp(string str) {
// return str;
//}
public UserInfo PostInfo([FromBody]string value) {
UserInfo userInfo = SimpleJson.SimpleJson.DeserializeObject<UserInfo>(value);
if (new DataBaseMsg().Add( userInfo.id, userInfo.username, userInfo.password))
{
userInfo.msg = "注册成功";
}
else
{
userInfo.msg = "注册失败";
}
return userInfo;
}
}
}
========================服务器端部署完毕====================
客户端用Unity:
代码文件夹:
Logon文件夹下: Canvas,Login,Reg,SimpleJson,UserInfo
Chat文件夹下:Chat,Msg,NetManager
-----------Canvas--------
public class Canves : MonoBehaviour {
public GameObject LogonPanel;
private void Awake()
{
GameObject obj = Instantiate(LogonPanel);
}
}
----------Login----------
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
public class Login : MonoBehaviour {
private string serverUrl = "http://127.0.0.1:10087";
private InputField UserName;
private InputField Password;
private Button LogonBtn;
private Button RegBtn;
public GameObject LogonPanel;
public GameObject RegPanel;
private void Awake()
{
UserName = this.transform.Find("UserName").GetComponent<InputField>();
Password = this.transform.Find("Password").GetComponent<InputField>();
LogonBtn = this.transform.Find("Logon").GetComponent<Button>();
RegBtn = this.transform.Find("Reg").GetComponent<Button>();
}
void Start () {
RegBtn.onClick.AddListener(RegHandle);
LogonBtn.onClick.AddListener(LogonHandle);
}
private void LogonHandle()
{
UserInfo user = new UserInfo();
user.username = UserName.text;
user.password = Password.text;
user.msg = "yangyangyang";
StartCoroutine(LogonGet(user));
}
private IEnumerator LogonGet(UserInfo user)
{
string s = SimpleJson.SimpleJson.SerializeObject(user);
string url = serverUrl + "/api/Test";
url += "?str=" + s;
WWW www = new WWW(url);
yield return www;
if (www.error == null & www.isDone)
{
UserInfo reserInfo = SimpleJson.SimpleJson.DeserializeObject<UserInfo>(www.text);
if (reserInfo.msg == "登陆成功")
SceneManager.LoadScene("Chat");
else
Debug.Log(reserInfo.msg);
}
else
{
Debug.Log(www.error);
}
}
private void RegHandle()
{
Destroy(LogonPanel);
GameObject obj = Instantiate(RegPanel);
}
}
--------------Reg---------------
using UnityEngine.UI;
public class Reg : MonoBehaviour {
private string serverUrl = "http://127.0.0.1:9012";
private InputField UserName;
private InputField Password;
private Button ReturnLogonBtn;
private Button RegBtn;
private InputField ID;
public GameObject LogonPanel;
public GameObject RegPanel;
private void Awake()
{
UserName = this.transform.Find("UserName").GetComponent<InputField>();
Password = this.transform.Find("Password").GetComponent<InputField>();
ID = this.transform.Find("Name").GetComponent<InputField>();
ReturnLogonBtn = this.transform.Find("ReturnLogon").GetComponent<Button>();
RegBtn = this.transform.Find("Reg").GetComponent<Button>();
}
void Start () {
ReturnLogonBtn.onClick.AddListener(ReturnLogon);
RegBtn.onClick.AddListener(RegHandle);
}
private void RegHandle()
{
UserInfo user = new UserInfo();
user.id = ID.text;
user.username = UserName.text;
user.password = Password.text;
user.msg = "";
StartCoroutine(RegPost(user));
}
private IEnumerator RegPost(UserInfo user)
{
string str = SimpleJson.SimpleJson.SerializeObject(user);
string url = serverUrl + "/api/Test";
WWWForm form = new WWWForm();
form.AddField("", str);
WWW www = new WWW(url, form);
yield return www;
if (www.error == null && www.isDone)
{
UserInfo userInfo = SimpleJson.SimpleJson.DeserializeObject<UserInfo>(www.text);
Debug.Log(userInfo.msg);
Destroy(RegPanel);
GameObject obj = Instantiate(LogonPanel);
}
}
private void ReturnLogon()
{
Destroy(RegPanel);
GameObject obj = Instantiate(LogonPanel);
}
}
-----------------SimpleJson------------
...
-------------------UserInfo-------------
...