using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace tcp {
class Program {
static void Main(string[] args) {
TcpClient client = new TcpClient(); //实例化 client.Connect("127.0.0.1", 8000); //连接到服务器,由于服务器运行在本机,所以这里使用本机ip地址 NetworkStream stream = client.GetStream();//创建networkstream if (stream.CanWrite == true)//判断是否可以发送数据 {
Byte[] mybyte = Encoding.UTF8.GetBytes("Hello");//将“hello”按utf-8编码,转成字节类型,存到数组里 stream.Write(mybyte, 0, mybyte.Length); } else {
Console.Write("无法写入"); client.Close(); stream.Close(); return; } if (stream.CanRead == true)//判断是否可以接收数据 {
Byte[] bytes = new byte[1024]; int j = stream.Read(bytes,0,bytes.Length);//获取接收到数据的长度 string returndata = Encoding.UTF8.GetString(bytes,0,j);//将接收的数据按utf-8编码转成字符串,存到returndata里 Console.Write("返回数据:{0}", returndata); } else {
Console.Write("无法读取数据"); client.Close(); stream.Close(); return; } stream.Close(); while (true) {
}//死循环,防止窗口关闭 } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace tcpserver {
class Program {
static void Main(string[] args) {
try {
int port = 8000;//端口号 IPAddress addr = IPAddress.Parse("127.0.0.1");//本机ip地址 TcpListener listener = new TcpListener(addr, port);//创建listener,并绑定到本机的ip地址 listener.Start();//开始监听 Byte[] bytes = new byte[10]; string data = null; Console.Write("wait for connecting......\n"); TcpClient client = listener.AcceptTcpClient();//等待客户端连接请求,没连接成功之前一直停留在这条语句上 Console.Write("connected\n"); data = null; NetworkStream stream = client.GetStream();//创建网络流 int i; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)//判断接收到的数据是否为空,当不为空是进入循环 {
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);//编码接收到的数据,并存到data Console.WriteLine("接受信息:{0}", data); data.ToUpper(); byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);//将接收到的数据转成发送的格式 stream.Write(msg, 0, msg.Length);//发送数据 Console.Write("发送信息:{0}", data); } client.Close(); listener.Stop(); } catch (SocketException e) {
Console.WriteLine(e); } while (true) {
}//死循环,防止程序运行完后窗口关闭 } } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214424.html原文链接:https://javaforall.net
