//客户端发送数据,等待服务器数据并接收
public static string Client(string cparam,int serverStrNum,string StrIp,string StrPort)
{
//
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(StrIp, int.Parse(StrPort));
//
NetworkStream stm = tcpclnt.GetStream();
//
UTF8Encoding asen = new UTF8Encoding();
byte[] ba = asen.GetBytes(cparam);
if (stm.CanWrite)
stm.Write(ba, 0, ba.Length);
//
byte[] bb = new byte[serverStrNum];
while (stm.Read(bb, 0, serverStrNum).ToString().Trim()=="") { }
if (stm.DataAvailable)
stm.Read(bb, 0,serverStrNum);
//
string req = System.Text.Encoding.UTF8.GetString(bb);
//
stm.Close();
tcpclnt.Close();
return req;
}
//服务器类
public class Server
{
//
bool ServerRun = true;
//
TcpListener tcpListener = null;
//
Thread SerTh;
//
IPEndPoint SerIpendPoint;
//
string[] parameter;
public static string Server(string sparam,string ip,string port)
{
//
SerIpendPoint= new IPEndPoint(IPAddress.Parse(ip), Int32.Parse(port));
tcpListener = new TcpListener(SerIpendPoint);
tcpListener.Start();
//
SerTh = new Thread(new ThreadStart(ServerWorking));
ServerRun = true;
SerTh.Start();
}
public bool StopServer()
{
try
{
ServerRun = false;
tcpListener.Stop();
SerTh.Abort();
return (true);
}
catch
{
return (false);
}
}
private void ServerWorking()
{
try
{
while (ServerRun)
{
Socket QS;
QS = TcpListener.AcceptSocket();
Byte[] Stream = new Byte[1024];
QS.Receive(Stream);
//
string clientStr = System.Text.Encoding.UTF8.GetString(Stream);
string serverStr = DataConvert(clientStr);
//
UTF8Encoding SendByte = new UTF8Encoding();
QS.Send((SendByte.GetBytes(serverStr)));
//string FileUrl;
//QS.SendFile(FileUrl);
QS.Close();
}
}
catch { }
}
private string DataConvert(string clientStr);
{
string serverStr=clientStr;
return serverStr;
}
private string[] SplitParam(string str,int ParamNum)
{
parameter = new string[ParamNum];//保存接收的参数
for (int i = 0; i < ParamNum; i++)
{
parameter[i] = "";
}
int j = 0;//参数指针
for (int i = 0; i < str.Length; i++)
{
if (str[i] != ';')
{
if (str[i] == '/0')
{
break;
}
parameter[j] += str[i].ToString().Trim();
}
else
{
j++;
}
}
return parameter;
}
}