using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; namespace WebSocket { public partial class WebSocketTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SocketServer socket = new SocketServer(1234, "192.168.88.196", TextBox1); //啓動線程 Thread thread = new Thread(new ThreadStart(socket.beginListen)); thread.Start(); // 在應用程序啓動時運行的代碼 //(new System.Threading.Thread(new System.Threading.ThreadStart(new Class1().CreatSocket))).Start();//開闢一個新線程 } } protected void Button1_Click(object sender, EventArgs e) { Socketclient client = new Socketclient(TextBox2, TextBox3); client.StartClient(); } } public class Socketclient { TextBox txt; TextBox send_txt; public Socketclient(TextBox txt, TextBox send_txt) { this.txt = txt; this.send_txt = send_txt; } public void StartClient() { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[4]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 1234); // Create a TCP/IP socket. Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); // Console.WriteLine("Socket connected to {0}",sender.RemoteEndPoint.ToString()); txt.Text += "\r\n" + sender.RemoteEndPoint.ToString() + "\r\n"; // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes(send_txt.Text + "<EOF>"); // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); //Console.WriteLine("Echoed test = {0}",Encoding.ASCII.GetString(bytes,0,bytesRec)); txt.Text += "\r\n" + Encoding.ASCII.GetString(bytes, 0, bytesRec) + "\r\n";//接收遠程服務器信息 // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (ArgumentNullException ane) { // Console.WriteLine("ArgumentNullException : {0}",ane.ToString()); txt.Text += "\r\n" + ane.ToString() + "\r\n"; } catch (SocketException se) { // Console.WriteLine("SocketException : {0}",se.ToString()); txt.Text += "\r\n" + se.ToString() + "\r\n"; } catch (Exception e) { // Console.WriteLine("Unexpected exception : {0}", e.ToString()); txt.Text += "\r\n" + e.ToString() + "\r\n"; } } catch (Exception e) { // Console.WriteLine( e.ToString()); txt.Text += "\r\n" + e.ToString() + "\r\n"; } } } public class SocketServer { int port; //端口 string host;//ip地址 TextBox txt; /// <summary> /// 構造涵數 /// </summary> /// <param name="ports">端口號</param> public SocketServer(int ports, string host,TextBox txt) { this.port=ports; this.host = host; this.txt = txt; } //開始監聽 public void beginListen(){ try { IPAddress ip = IPAddress.Parse(host);//把ip地址字符串轉換爲IPAddress類型的實例 IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint類的新實例 ///建立socket並開始監聽 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立一個socket對像,若是用udp協議,則要用SocketType.Dgram類型的套接字 s.Bind(ipe);//綁定EndPoint對像(端口和ip地址) s.Listen(0);//開始監聽 txt.Text += "等待客戶端鏈接"; // Console.WriteLine("等待客戶端鏈接"); //定義循環,以即可以簡歷屢次鏈接 while (true) { Socket temp = s.Accept();//爲新建鏈接建立新的socket while (true) { string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//從客戶端接受信息 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); txt.Text += "\r\n" + recvStr + "\r\n"; if (recvStr.IndexOf("<EOF>") > -1) { break; } } //給client端返回信息 // Console.WriteLine("server get message:{0}", recvStr);//把客戶端傳來的信息顯示出來 string sendStr = "jpeg upload OK"; byte[] bs = Encoding.ASCII.GetBytes(sendStr); temp.Send(bs, bs.Length, 0);//返回信息給客戶端 temp.Shutdown(SocketShutdown.Both); temp.Close(); } } catch (Exception ex) { string str = ex.ToString(); txt.Text += "\r\n" + str + "\r\n"; } } } }
<body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" Height="206px" TextMode="MultiLine" Width="700px" ></asp:TextBox> <hr /> <asp:TextBox ID="TextBox2" runat="server" Height="197px" TextMode="MultiLine" Width="376px"></asp:TextBox> <asp:TextBox ID="TextBox3" runat="server" Height="119px" TextMode="MultiLine"></asp:TextBox> <asp:Button ID="Button1" runat="server" Height="52px" OnClick="Button1_Click" Text="SEND" Width="138px" /> </div> </form> </body>