好久没写博客了,我也发现我堕落了,天天看连续剧。还有就是我想在北京找份unity3d程序员的工作,随时可以去上班,有合适的话,麻烦大侠们给我介绍介绍哈。我的QQ:397319689(有点笨),呵呵~~~
最近几天都在搞unity操作Sql server,也用到了底层通信的东西,局域网测试是通过了的,要谢谢我龙哥(灰太龙),他太厉害了,呵呵~~~源代码我忘记拷贝过来了,所以大概写了一下,我发现OnGUI里面的UI在服务端不大好弄啊,我这里没有用到多线程,用到了数组。
0.看看思路:
1.安装好sqlserver还需要一些dll文件,unity本身里面就有的,在路径E:\Unity\Editor\Data\Mono\lib\mono\2.0下有I18N.dll,I18N.CJK.dll和I18N.West.dll,以及System.Data.dll。
我这里安装的是sqlserver2005开发版。http://www.cnblogs.com/icewee/articles/2019783.html
2.那就是建表咯,这个就不多说了啊。
3.服务端连接数据库。
连接数据库:
con = new SqlConnection("Data Source=WANGXF;User ID=sa;Password=sa;database=data1"); con.Open();查找读取数据库:
SqlDataReader Select(string content){ SqlCommand cmd=new SqlCommand(content,con); SqlDataReader reader = cmd.ExecuteReader(); return reader; }
修改,增加:
void Reset(string content){ SqlCommand cmd =new SqlCommand(content,con); cmd.ExecuteNonQuery(); }
4.客户端和服务端同学
服务端:
using System.Net;using System;public class Sender{ NetworkStream stream; /*服务器端开启监听*/ public TcpListener open(){ TcpListener server=null; string ip="192.168.1.103"; int iport=5561; IPAddress address=IPAddress.Parse(ip); server=new TcpListener(address,iport); server.Start(); return server; } /*添加正在向服务端发送请求的客户端*/ public TcpClient addClient(TcpListener server){ TcpClient client=null; if(server.Pending()){ client = server.AcceptTcpClient(); } return client; } /*向客户端发送消息*/ public void send(ArrayList clients,string data) { byte[] msg = System.Text.Encoding.UTF8.GetBytes(data); for(int i=0;i<clients.Count;i++){ stream = (clients[i] as TcpClient).GetStream(); stream.Write(msg,0,msg.Length); } } /*接收客户端的消息*/ public string receive (ArrayList clients) { Byte[] bytes = new Byte[4096]; string data=""; int i=0; for(int j=0;j<clients.Count;j++){ if((clients[j] as TcpClient).Available!=0){ stream = (clients[j] as TcpClient).GetStream(); if((i = stream.Read(bytes,0, bytes.Length))!=0) { data = System.Text.Encoding.UTF8.GetString(bytes, 0, i); } if(data.Contains("Exit")){ (clients[j] as TcpClient).Close(); clients.RemoveAt(j); } } } return data; } }
客户端:
using UnityEngine;using System.Collections;using System.Net.Sockets;using System.Net;using System.Text;using System.IO;using System;public class Receiver{ /*连接服务器端*/ public void connect(TcpClient client) { string ip="192.168.1.103"; int iport=5561; client.Connect(ip, iport); } /*接收服务器端消息*/ public string receive (TcpClient client) { string data=""; int i=0; Byte[] bytes = new Byte[4096]; NetworkStream stream = client.GetStream(); if(client.Available!=0){ if((i = stream.Read(bytes,0, bytes.Length))!=0) { data = System.Text.Encoding.UTF8.GetString(bytes, 0, i); } } return data; } /*向服务器端发送消息*/ public void send(TcpClient client,string data) { NetworkStream stream = client.GetStream(); byte[] msg = System.Text.Encoding.UTF8.GetBytes(data); stream.Write(msg,0,msg.Length); }}
以上只是一些主要的内容,我把工程放到我的资源里面了。http://download.csdn.net/detail/dlnuchunge/4734166
以上内容都是我乱盖的,不足的地方往大家见谅,多多指点~~~~