当前位置:编程学习 > C#/ASP.NET >>

C# SOCKET网络编程

程序片段:

public void StartListen()
{
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
lisThd = new Thread(new ThreadStart(MainListener));
lisThd.ApartmentState = ApartmentState.STA;
lisThd.Start();
}
/// <summary>
/// 监听主线程
/// </summary>
void MainListener()
{
listener.Listen(10); ///每次程序执行到这里,下面的就不执行了
while (true)
{
client = listener.Accept();
NetConn conn = new NetConn(client);
tmpByte = conn.Receive();
}
}

有没有高手帮我解答一二

追问:同步tcpclient我已经会了,我主要是想了解下socket怎么用!

答案:1. 把 lisThd.ApartmentState = ApartmentState.STA; 注释掉,ApartmentState 已过时。

2. 如果使用TCP协议,建议你使用 TcpListener 类和 TcpClient 类,更加方便。以下是一个示例

以下示例说明如何设置 TcpClient 以连接到 TCP 端口 13 上的时间服务器。
using System;
using System.Net.Sockets;
using System.Text;

public class TcpTimeClient {
private const int portNum = 13;
private const string hostName = "host.contoso.com";

public static int Main(String[] args) {
try {
TcpClient client = new TcpClient(hostName, portNum);

NetworkStream ns = client.GetStream();

byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length);

Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead));

client.Close();

} catch (Exception e) {
Console.WriteLine(e.ToString());
}

return 0;
}
}

TcpListener 用于监视 TCP 端口上的传入请求,然后创建一个 Socket 或 TcpClient 来管理与客户端的连接。Start 方法启用侦听,而 Stop 方法禁用端口上的侦听。AcceptTcpClient 方法接受传入的连接请求并创建 TcpClient 以处理请求,AcceptSocket 方法接受传入的连接请求并创建 Socket 以处理请求。

以下示例说明如何使用 TcpListener 创建网络时间服务器以监视 TCP 端口 13。当接受传入的连接请求时,时间服务器用来自宿主服务器的当前日期和时间进行响应。

using System;
using System.Net.Sockets;
using System.Text;

public class TcpTimeServer {

private const int portNum = 13;

public static int Main(String[] args) {
bool done = false;

TcpListener listener = new TcpListener(portNum);

listener.Start();

while (!done) {
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();

Console.WriteLine("Connection accepted.");
NetworkStream ns = client.GetStream();

byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());

try {
ns.Write(byteTime, 0, byteTime.Length);
ns.Close();
client.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

listener.Stop();

return 0;
}

}


上一个:如何简单学习C#
下一个:关于C#的问题

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,