客户端写入服务器 - 服务器读取。和服务器写入客户端 - 客户端未读取。
服务器:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
class SocketServer
{
public static void Main()
{
StreamReader streamReader;
NetworkStream networkStream;
TcpListener tcpListener = new TcpListener(5555);
tcpListener.Start();
Console.WriteLine("The Server has started on port 5555");
Socket serverSocket = tcpListener.AcceptSocket();
try
{
if (serverSocket.Connected)
{
Console.WriteLine("Client connected");
networkStream = new NetworkStream(serverSocket);
AsynchronousMethodDelegate asyncDeleg = new AsynchronousMethodDelegate(AsynchronousMethod);
AsyncCallback callback = new AsyncCallback(CallbackMethod);
asyncDeleg.BeginInvoke(networkStream, callback, asyncDeleg);
streamReader = new StreamReader(networkStream);
while (true)
{
Console.WriteLine(streamReader.ReadLine());
}
}
if (serverSocket.Connected)
serverSocket.Close();
Console.Read();
}
catch (SocketException ex)
{
Console.WriteLine(ex);
}
catch (IOException ex) { Console.WriteLine(ex); }
}
private static void CallbackMethod(IAsyncResult ar)
{
AsynchronousMethodDelegate asyncDeleg = (AsynchronousMethodDelegate)ar.AsyncState;
}
private delegate void AsynchronousMethodDelegate(NetworkStream networkStream);
private static void AsynchronousMethod(NetworkStream networkStream)
{
try
{
StreamWriter streamWriter;
streamWriter = new StreamWriter(networkStream);
while (true)
{
streamWriter.WriteLine(Console.ReadLine());
}
}
catch (SocketException ex){}
}
}
客户:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
class SocketClient
{
static void Main(string[] args)
{
TcpClient tcpClient;
NetworkStream networkStream;
StreamWriter streamWriter;
try
{
tcpClient = new TcpClient("localhost", 5555);
networkStream = tcpClient.GetStream();
AsynchronousMethodDelegate asyncDeleg = new AsynchronousMethodDelegate(AsynchronousMethod);
AsyncCallback callback = new AsyncCallback(CallbackMethod);
asyncDeleg.BeginInvoke(networkStream, callback, asyncDeleg);
streamWriter = new StreamWriter(networkStream);
while (true)
{
streamWriter.WriteLine(Console.ReadLine());
streamWriter.Flush();
//Console.WriteLine(streamReader.ReadLine());
}
//Console.Read();
}
catch (SocketException ex){
Console.WriteLine(ex);
}
}
private static void CallbackMethod(IAsyncResult ar)
{
AsynchronousMethodDelegate asyncDeleg = (AsynchronousMethodDelegate)ar.AsyncState;
//lblCallback.Text = asyncDeleg.EndInvoke(ar);
}
private delegate void AsynchronousMethodDelegate(NetworkStream networkStream);
private static void AsynchronousMethod(NetworkStream networkStream)
{
try
{
StreamReader streamReader = new StreamReader(networkStream);
while (true)
{
Console.WriteLine(streamReader.ReadLine());
}
}
catch (SocketException ex) { }
catch (IOException ioex) { }
}
}