纳金网
标题:
C# 客户端服务器Socket
[打印本页]
作者:
刀锋狼
时间:
2015-7-31 00:49
标题:
C# 客户端服务器Socket
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
public class ServerSocket {
public string ipStr;
public int port;
public int maxConnections;
public bool IsRun {
get {
return isRun;
}
}
private Socket serverSocket;
private Thread serverThread;
private bool isRun;
private Socket temp;
public ServerSocket (string ipStr, int port = 2333, int maxConnections = 50) {
isRun = false;
this.ipStr = ipStr;
this.port = port;
this.maxConnections = maxConnections;
serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind (new IPEndPoint (IPAddress.Parse (ipStr), port));
serverSocket.Listen (maxConnections);
serverThread = new Thread (new ThreadStart (AsyncServer));
}
public void StartServer () {
isRun = true;
serverThread.Start ();
}
public void StopServer () {
isRun = false;
serverSocket.Close ();
if (serverThread.IsAlive) {
serverThread.Abort ();
}
}
private ServerSocket () {
}
private void AsyncServer () {
while (isRun) {
Socket userSocket = serverSocket.Accept ();
temp = userSocket;
Thread tt = new Thread (new ThreadStart (XXX));
tt.Start ();
}
}
private void XXX () {
Socket user = temp;
while (true) {
byte [] receivedData = new byte [1024];
user.Receive (receivedData);
string m = Encoding.UTF8.GetString (receivedData);
Debug.Log (m);
if (m != "") {
byte [] s = Encoding.UTF8.GetBytes (m);
user.Send (s);
}
}
}
}
复制代码
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
using UnityEngine.UI;
public class Client : MonoBehaviour {
public string ipStr;
public int port;
public InputField t;
public Text text;
private string str = "";
Socket s;
void Start () {
s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect (new IPEndPoint (IPAddress.Parse (ipStr), port));
Thread tt = new Thread (new ThreadStart (DDD));
tt.Start ();
}
private void DDD () {
while (true) {
byte [] r = new byte [1024];
s.Receive (r);
str = Encoding.UTF8.GetString (r);
}
}
void Update () {
text.text = str;
if (Input.GetKeyDown (KeyCode.S)) {
byte [] sendbuf = Encoding.UTF8.GetBytes (t.text);
s.Send (sendbuf);
}
}
}
复制代码
作者:
GPSGIS3D
时间:
2017-5-5 13:57
水平一般般
欢迎光临 纳金网 (http://rs.narkii.com/club/)
Powered by Discuz! X2.5