python客户端
看注释,注释写的很清楚,copy粘贴即可运行
# coding=utf-8
# 使用utf-8编码
# 版本为python 2.*
import socket
# the max player number
playerNumber = 10
# host and port
host = "127.0.0.1"
port = 12345
# 创建socket,TCP类型的
mySocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定IP和端口
mySocket.bind((host,port))
# 开始监听
mySocket.listen(playerNumber)
# 发送一个
conn,addr = mySocket.accept()
data = "你好张三,你必死\n"
conn.send(data)
# 接收一个
theGetMessage = conn.recv(1024)
print theGetMessage
# 关闭
conn.close()
mySocket.close()
C#客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace TCP客户端
{
class Program
{
static void Main(string[] args)
{
//创建socket
Socket mySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//链接
mySocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345));
//接收消息
byte[] dataBytes = new byte[1024];
int count = mySocket.Receive(dataBytes);
string result = Encoding.UTF8.GetString(dataBytes, 0, count);
Console.Write(result);
//发送一条消息
string sendData = Console.ReadLine();
mySocket.Send(Encoding.UTF8.GetBytes(sendData));
mySocket.Close();
}
}
}
运行结果