一,最简单的没有线程的代码
1、服务端
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Net;
usingSystem.Net.Sockets;
namespaceservers
{
class myServer
{
///<summary>
///启动监听:监听客户机请求
///</summary>
public voidmyStartUp()
{
IPAddresss_ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
TcpListenerm_listen = new TcpListener(s_ip,8888);
m_listen.Start();
Console.WriteLine("已经启监听程序,正在监听中...!");
while(true)
{
///接受到client连接,为此连接建立新的socket,并接受信息
TcpClientc_pc = m_listen.AcceptTcpClient();//接受客户端的连接(建立连接)
Console.WriteLine("有新用户连接");
NetworkStreamns=c_pc.GetStream();
byte[]bytes = new byte[1024];
ns.Read(bytes, 0, 1024);//从System.Net.Sockets.NetworkStream 读取数据
stringdataContent = Encoding.Unicode.GetString(bytes,0, bytes.Length);//将指定字节数组中的一个字节序列解码为一个字符串。
Console.WriteLine(c_pc.Client.AddressFamily.ToString()+ "--" + dataContent);//将输出到控制台。将指定的字符串值(后跟当前行终止符)写入标准输出流。
bytes = Encoding.Unicode.GetBytes(dataContent.ToUpper());//将字符串转换成大写字母后,再将字符编码为一个字节序列。
ns.Write(bytes, 0,bytes.Length);//将数据写入流。(将数据写入 System.Net.Sockets.NetworkStream)
}
}
}
}