最近突然感觉Socket编程很重要,所以自己写了一个简单的小程序
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Client
{
class CClient
{
public string ReturnStr = "";
public void BeginSend()
{
//string ip = "192.168.110.1";
string port = "8080";
//获取服务器的ip
IPAddress serverIp = GetServerIP();
//取出端口
int serverPort = Convert.ToInt32(port);
//连接指定ip和端口号得机子
IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
//定义一个自己的信息
byte[] byteMessage;
//其中AddressFamily.InterNetwork参数指定 Socket 使用的寻址方案,
//SocketType.Stream参数指定 Socket 的类型,
//ProtocolType.Tcp 参数指定 Socket 使用的协议。
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
socket.Connect(iep);
//定义一个信息流
byteMessage = Encoding.Default.GetBytes("你好吗?我是您的朋友");
//发送信息
socket.Send(byteMessage);
//接收数据
int rec = socket.Receive(byteMessage);
if (rec >0)
{
//获取现在的时间
string sTime = DateTime.Now.ToShortTimeString();
string msg = sTime + ":" + "Message from:";
//获取信息
msg += socket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
ReturnStr = msg;
}
//关闭网络连接
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
/// <summary>
/// 获取IP
/// </summary>
/// <returns></returns>
public static IPAddress GetServerIP()
{
IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Client
{
class CClient
{
public string ReturnStr = "";
public void BeginSend()
{
//string ip = "192.168.110.1";
string port = "8080";
//获取服务器的ip
IPAddress serverIp = GetServerIP();
//取出端口
int serverPort = Convert.ToInt32(port);
//连接指定ip和端口号得机子
IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
//定义一个自己的信息
byte[] byteMessage;
//其中AddressFamily.InterNetwork参数指定 Socket 使用的寻址方案,
//SocketType.Stream参数指定 Socket 的类型,
//ProtocolType.Tcp 参数指定 Socket 使用的协议。
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
socket.Connect(iep);
//定义一个信息流
byteMessage = Encoding.Default.GetBytes("你好吗?我是您的朋友");
//发送信息
socket.Send(byteMessage);
//接收数据
int rec = socket.Receive(byteMessage);
if (rec >0)
{
//获取现在的时间
string sTime = DateTime.Now.ToShortTimeString();
string msg = sTime + ":" + "Message from:";
//获取信息
msg += socket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
ReturnStr = msg;
}
//关闭网络连接
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
/// <summary>
/// 获取IP
/// </summary>
/// <returns></returns>
public static IPAddress GetServerIP()
{
IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
}
}
}