UDP 서버 코드
2513 단어 네트워크 링크
//
Socket socket; // socket
EndPoint clientEnd; //
IPEndPoint ipEnd; //
string recvStr; //
string sendStr; //
byte[] recvData = new byte[1024]; // ,
byte[] sendData = new byte[1024]; // ,
int recvLen; //
Thread connectThread; //
//
void InitSocket()
{
// , IP
ipEnd = new IPEndPoint(IPAddress.Any, 8001);
// ,
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// ip
socket.Bind(ipEnd);
//
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
clientEnd = (EndPoint)sender;
print("waiting for UDP dgram// UDP ");
// , ,
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
void SocketSend(string sendStr) //
{
//
sendData = new byte[1024];
//
sendData = Encoding.ASCII.GetBytes(sendStr);
//
socket.SendTo(sendData, sendData.Length, SocketFlags.None, clientEnd);
}
//
void SocketReceive()
{
//
while (true)
{
// data
recvData = new byte[1024];
// , ,
recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
print("message from// : " + clientEnd.ToString()); //
//
recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
print(recvStr);
//
sendStr = "From Server : " + recvStr;
SocketSend(sendStr);
}
}
//
void SocketQuit()
{
//
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
// socket
if (socket != null)
socket.Close();
print("disconnect");
}
// Use this for initialization
void Start()
{
InitSocket(); // server
}
void OnApplicationQuit()//
{
SocketQuit();
}
모르는 것이 있으면 저에게 비밀로 하거나 QQ 채팅방을 추가할 수 있습니다. 636926481.
서로 교류!