应用程序的通信(急)

YiQiJinBu 2011-05-20 02:27:09
求教高手:
我做了一个Window Form聊天的程序(单机版),我想把它升级成能在局域网中能聊天的东西,怎么做?我查过,这似乎要用到TCP通信,有没有实例和详细的讲解啊,介绍一下,讲一讲啊....
...全文
107 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yysaaaa 2011-05-20
  • 打赏
  • 举报
回复
服务器:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication1
{
class Program1
{
static void Main(string[] args)
{
int receive;
byte[] date = new byte[1024];
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsocket.Bind(iep);
newsocket.Listen(10);
Console.WriteLine("Waiting for a message for client");
Socket client = newsocket.Accept();
IPEndPoint clintiep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clintiep.Address, clintiep.Port);
string welcome = " welecome to my sever";
date = Encoding.ASCII.GetBytes(welcome);
client.Send(date, date.Length, SocketFlags.None);
while (true)
{
date = new byte[1024];
receive = client.Receive(date);
if (receive == 0)
{
break;
}
Console.WriteLine(Encoding.ASCII.GetString(date, 0, receive));
string input = "";
input = Console.ReadLine();
date = Encoding.ASCII.GetBytes(input);
receive = date.Length;
client.Send(date, receive, SocketFlags.None);
}
Console.WriteLine("disconnceted with {0}", clintiep.Address);
client.Close();
newsocket.Close();
}
}
}
客户端:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace client
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[1024];
string input, stringdate;
IPAddress local = IPAddress.Parse("192.168.1.227");
IPEndPoint iep = new IPEndPoint(local,9050);
Socket sever=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sever.Connect(iep);
}
catch (SocketException e)
{
Console.WriteLine("无法连接到服务器");
Console.WriteLine(e.ToString());
}
finally
{

}
int recive = sever.Receive(data);
stringdate = Encoding.ASCII.GetString(data, 0, recive);
while (true)
{
input = Console.ReadLine();
if (input == "exit")
{
break;
}
sever.Send(Encoding.ASCII.GetBytes(input));
int rec = sever.Receive(data);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, rec));
}
Console.WriteLine("断开与服务器的连接.....");
sever.Close();
}
}
}
这是控制台程序,好久以前的不知道行不行
bdmh 2011-05-20
  • 打赏
  • 举报
回复
socket通信
wetcom 2011-05-20
  • 打赏
  • 举报
回复
使用TcpClient 和TcpListener 这两个类就可以实现了
LBreathy 2011-05-20
  • 打赏
  • 举报
回复
网上有很多实例~楼主可以找下!

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧