服务器端程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;
namespace server
{
class Program
{
static void Main(string[] args)
{
try
{
//第一步:打开监听端口
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener tcpListener = new TcpListener(ip, 8001);
tcpListener.Start();
Console.WriteLine("开启端口服务....");
Console.WriteLine("本地节点:" + tcpListener.LocalEndpoint);
Console.WriteLine("等待连接.....");
bool loop=true;
Socket s = null;
//第二步:接受连接
while (loop)
{
s = tcpListener.AcceptSocket();
Console.WriteLine("连接来自:" + s.RemoteEndPoint);
//第三步:接收客户端信息
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("已接收");
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
}
//第四步:回应客户端
ASCIIEncoding a = new ASCIIEncoding();
s.Send(a.GetBytes("The string was recieved by the server"));
//第五步:释放资源,断开连接
}
s.Close();
tcpListener.Stop();
Console.ReadLine();
}
catch (Exception ee)
{
Console.WriteLine("Error:{0}", ee.Message);
Console.ReadLine();
}
}
}
}
客户端程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace client
{
class Program
{
static void Main(string[] args)
{
try
{
//第一步:新建客户端
TcpClient client = new TcpClient();
Console.WriteLine("连接...");
//第二步:连接服务器
client.Connect("127.0.0.1", 8001);
Console.WriteLine("已连接!");
Console.WriteLine("请输入要传送的字符串:");
//第三步:获得客户端流
string s = Console.ReadLine();
Stream stream = client.GetStream();
//第四步:发送信息
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] ba = ascii.GetBytes(s);
Console.WriteLine("传输中....");
stream.Write(ba, 0, ba.Length);
//第五步:接收服务器返回信息
byte[] bb = new byte[100];
string res = "";
int k = stream.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
{
res += Convert.ToChar(bb[i]);
}
Console.WriteLine(res);
//第六步:关闭客户端连接
client.Close();
Console.ReadLine();
}
catch(Exception ee)
{
Console.WriteLine("Error:{0}", ee.Message);
}
}
}
}
编译后先启动服务器程序,再启动客户端程序