8年前,令我窒息的Java socket体验学习

时间:2021-11-09 01:30:43

本来已经放弃编程了,那时我发誓再也不去IT培训班了,如果找不到工作,我就去工地上打工。可心有不甘,老是惦记着,我不想天天面对生产线,做一个丧失思考能力的操作工,可后来呀,还是走上了程序员之路。。。这么多年了,接触到C#的socket编程,可我还能感受到当时想去洋谷科技而又不能的那种无奈,迷茫。

我不会Java,仅用C#来说明,用socket实现聊天功能,代码是网上抄的,但可以说明当年我感觉高深的socket编程

Server:

 using System;
using System.Net;
using System.Net.Sockets;
using System.IO; namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
TcpClient client=null;
try
{
IPAddress myIp=IPAddress.Parse("127.0.0.1");
TcpListener myServer = new TcpListener(myIp, ); myServer.Start();
Console.WriteLine("Wait for client's connection...."); client = myServer.AcceptTcpClient();
Console.WriteLine("Client is already connected..."); NetworkStream stream = client.GetStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream); while(true)
{
Console.WriteLine("\nClient:\n" + sr.ReadLine()+"\n");
Console.WriteLine("Server:");
string msg= Console.ReadLine();
sw.WriteLine(msg);
sw.Flush();
}
}
catch
{
if(client!=null)
{
client.Dispose();
}
}
}
}
}

Client:

 using System;
using System.IO;
using System.Net;
using System.Net.Sockets; namespace TCPClient
{
class Program
{
static void Main(string[] args)
{
TcpClient client=null;
try
{
IPAddress myIp = IPAddress.Parse("127.0.0.1");
client = new TcpClient();
client.Connect(myIp, );
Console.WriteLine("server connected...please enter contact content..."); NetworkStream stream = client.GetStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream); while (true)
{
Console.WriteLine("Client:");
string msg = Console.ReadLine();
sw.WriteLine(msg);
sw.Flush();
Console.WriteLine("\nServer:\n" + sr.ReadLine()+"\n");
}
}
catch
{
if(client!=null)
{
client.Dispose();
}
}
}
}
}

先运行Server端

8年前,令我窒息的Java socket体验学习

看到Wait for client's connection... 后,运行client端

8年前,令我窒息的Java socket体验学习

然后,client端发送信息"Hi Server, I am from client."到server端,server端收到client发来的消息

8年前,令我窒息的Java socket体验学习

然后,server端发送信息"Hi Client, I am from Server."到client端,client端收到server发来的消息

8年前,令我窒息的Java socket体验学习

按Ctrl+c先后中断客户端和服务端。