这几天研究了下Socket交互。
通过网上的资料做了有关Socket的第一个Demo,虽然不是很成熟,但个人感觉已经相对比较完整了。各类型数据的传输接受都有,其中也做了float类型的(因为我感觉做Unity应该用的着)。
功能方面,为了测试多用户交互,我在Demo上开启了4个Socket 4个线程接受数据。实现了服务端通知用户进入 离开功能。
真机上,需要加上字库,要不无法显示中文。
工程目录:
下面上代码:
客户端代码:
using UnityEngine;
using System;
using System.Collections;
using LSocket.Net;
using LSocket.Type;
using LSocket.cmd;
public class SocketDemo : MonoBehaviour
{
public UnitySocket[] socket;
public String[] textAreaString;
public String[] textFieldString;
public GUISkin mySkin;
// Use this for initialization
void Start()
{
socket = new UnitySocket[4];
textAreaString = new String[12];
for (int i = 0; i < 12; i++)
{
textAreaString[i] = "";
}
textFieldString = new String[4];
for(int i=0;i<4;i++){
textFieldString[i] = "";
}
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
GUI.skin = mySkin;
for (int i = 0; i < 4; i++)
{
String s = textAreaString[i * 3] + "\n" + textAreaString[i * 3 + 1] + "\n" + textAreaString[i * 3 + 2];
GUI.TextArea(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2) + 50, 100, 60), s);
textFieldString[i] = GUI.TextField(new Rect(i % 2 * Screen.width / 2+50, i / 2 * (Screen.height / 2), 100, 20), textFieldString[i]);
if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2), 40, 20), "连接"))
{
socket[i] = null;
socket[i] = new UnitySocket();
socket[i].SocketConnection("192.168.0.8", 10000, this, i);
socket[i].DoLogin(textFieldString[i]);
}
else if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 *( Screen.height / 2) + 25, 40, 20), "关闭"))
{
if (socket[i] != null)
{
socket[i].close();
socket[i] = null;
}
}
}
if (GUI.Button(new Rect(Screen.width - 60, Screen.height - 30, 60, 30), "退出")) {
Application.Quit();
}
}
}
namespace LSocket.Net
{ /**
*
* @author feng侠,qq:313785443
* @date 2010-12-23
*
*/
// 描 述:封装c# socket数据传输协议
using UnityEngine;
using System;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Text;
using System.Threading;
using LSocket.Type;
using LSocket.cmd;
class SocketThread
{
UnitySocket socket;
SocketDemo demo;
int idx;
public SocketThread(UnitySocket socket, SocketDemo demo, int idx)
{
this.socket = socket;
this.demo = demo;
this.idx = idx;
}
public void run()
{
while (true)
{
try
{
String s = socket.ReceiveString();
demo.textAreaString[idx * 3] = demo.textAreaString[idx * 3 + 1];
demo.textAreaString[idx * 3 + 1] = demo.textAreaString[idx * 3 + 2];
demo.textAreaString[idx * 3 + 2] = s;
MonoBehaviour.print(s + " " + idx);
}
catch (Exception e)
{
MonoBehaviour.print(e.ToString());
socket.t.Abort();
}
}
}
}
public class UnitySocket
{
public Socket mSocket = null;
public Thread t=null;
private SocketThread st=null;
public SocketDemo demo=null;
public UnitySocket()
{
}
public void SocketConnection(string LocalIP, int LocalPort,SocketDemo demo,int idx)
{
this.demo=demo;
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress ip = IPAddress.Parse(LocalIP);
IPEndPoint i