本文介绍了Client server socket编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
服务器编码
Server coding
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace MultiCon
{
class Listener
{
Socket s;
public bool Listening
{
get;
private set;
}
public int Port
{
get;
private set;
}
public Listener(int port)
{
Port= port;
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void start()
{
if (Listening)
return;
s.Bind(new IPEndPoint(0, Port));
s.Listen(0);
s.BeginAccept(callback, null);
Listening = true;
}
public void stop()
{
if (!Listening)
return;
s.Close();
s.Dispose();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
void callback(IAsyncResult ar)
{
try
{
Socket s = this.s.EndAccept(ar);
if (SocketAccepted != null)
{
SocketAccepted(s);
}
this.s.BeginAccept(callback, null);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
public delegate void SocketAcceptedHandler(Socket e);
public event SocketAcceptedHandler SocketAccepted;
}
}
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.Windows.Forms;
namespace MultiCon
{
class Program
{
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}
客户端编程
Client Side Programming
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace MultiCon_C
{
public partial class Main : Form
{
Socket sck;
public Main()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
private void btnconnect_Click(object sender, EventArgs e)
{
sck.Connect("192.168.201.5", 22);
MessageBox.Show("Connected");
}
private void btnsend_Click(object sender, EventArgs e)
{
int s=sck.Send(Encoding.Default.GetBytes(txtMsg.Text));
if(s>0)
{
MessageBox.Show("Data Sent");
}
}
private void btnclose_Click(object sender, EventArgs e)
{
sck.Close();
sck.Dispose();
Close();
}
private void txtMsg_TextChanged(object sender, EventArgs e)
{
}
}
}
我尝试过:
我在运行代码时遇到此错误在客户端的连接按钮上。
System.Net.Sockets.SocketException(0x80004005):连接尝试失败,因为连接方没有正确响应一段时间,或建立的连接失败,因为连接的主机无法响应
What I have tried:
I m getting this error while running the code clicking on the connect button from the client side.
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
推荐答案
这篇关于Client server socket编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!