花了點時間參考網路資料,寫了一個console,下面有說明文字!!
===============================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace consoleserver02
{
class Program
{
static void Main(string[] args)
{
int port=8765;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,port);//設定IP
// IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.50.130"), 8887);
Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//設定server的IP
newsock.Bind(ipep);//如果您打算要接收多點傳送資料包,則必須以多點傳送通訊埠編號呼叫 Bind 方法。
newsock.Listen(10);//連線數量,呼叫 Listen 方法之前呼叫 Bind。 使用 Connect 方法之前並不需要呼叫 Bind
Console.WriteLine("server Start.....");
Console.WriteLine("server ip="+ipep);
Console.WriteLine("server port="+port.ToString());
while(true)//進入迴圈,不斷接收資料,client除非要不斷讀取資料,否則不需要用到while
{
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("client end point="+ clientep);
TcpListener listener = new TcpListener(client);
Thread thread = new Thread(new ThreadStart(listener.run));
thread.Start();//啟動thread
}
//newsock close();
}
}
public class TcpListener
{
Socket socket;
public TcpListener(Socket S)
{
socket = S;
}
public void run()
{
try
{
while (true)
{
byte[] data = new byte[1024];
int recv = socket.Receive(data);//接受資料
if (recv == 0) break;//接受到 client的資料,才會將server資料送給client
Thread.Sleep(100);//等待0.1 sec後,再送資料給client
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));//byte轉字串
data = Encoding.UTF8.GetBytes("hello I am server"+"/");//server送出去的資料data
int i = socket.Send(data);//資料的長度
Console.WriteLine("Sent {0} bytes to client.", i);//輸出資料長度
Thread.Sleep(2000);//server每兩秒執行一次
}
socket.Close();
}
catch (Exception e)//錯誤的訊息
{
Console.WriteLine("client"+socket.RemoteEndPoint+"Error:close");
Console.WriteLine(e);
}
}
}
}
留言列表