C#--TCP例項(實現了client)
阿新 • • 發佈:2018-11-20
如果你耐得住寂寞,這個聊天軟體你可以玩一年
這是客戶端的程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//新增新的名稱空間
using System.Net;
using System.Net.Sockets;
using System.IO; //流StreamReader
namespace SocketClient
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//設定伺服器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置伺服器IP與埠
Console.WriteLine("連線伺服器成功");
}
catch
{
Console.WriteLine("連線伺服器失敗,請按回車鍵退出!");
return;
}
while (true)
{
//通過clientSocket接收資料
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("接收伺服器訊息:/n {0}", Encoding.ASCII.GetString(result, 0, receiveLength));
string ss = "console:/n "+Console.ReadLine();
clientSocket.Send(Encoding.ASCII.GetBytes(ss));
}
}
}
}
然後我就呼叫這個:
作為tcp的伺服器,就可以一起聊天了哈哈哈