110,534
社区成员
发帖
与我相关
我的任务
分享
public void Main()
{
try
{
int port = 58547;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
s.Bind(ipe);//绑定端口
s.Listen(0);//开始监听
//Console.WriteLine("Wait for connect");
Socket temp = s.Accept();//为新建连接创建新的Socket。
//Console.WriteLine("Get a connect");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
string sendStr = "Ok!Client Send Message Sucessful!";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);//返回客户端成功信息
temp.Close();
s.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
<div>
<asp:TextBox ID="TextBox1" runat="server" Height="206px" TextMode="MultiLine" Width="700px" ></asp:TextBox>
</div>
<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" />
public class SocketServer
{
int port; //端口
string host;//ip地址
TextBox txt;
TextBox txt2;
/// <summary>
/// 构造涵数
/// </summary>
/// <param name="ports">端口号</param>
public SocketServer(int ports, string host, TextBox txt,TextBox txt2)
{
this.port = ports;
this.host = host;
this.txt = txt;
this.txt2 = txt2;
}
//开始监听
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(10);//开始监听
//txt.Text += "等待客户端连接";
//定义循环,以便可以简历多次连接
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);
Console.WriteLine("server get message:{0}", recvStr);
if (recvStr.IndexOf("<EOF>") > -1)
{
break;
}
}
//给client端返回信息
//Console.WriteLine("server get message:{0}", recvStr);//把客户端传来的信息显示出来
string sendStr = "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";
}
}
}