服务器端: using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace QTCPServer1
{
class QServer1
{
[STAThread]
static void Main(string[] args)
{
QServer1 qServer = new QServer1();
TcpListener listener;
try
{
listener = new TcpListener(60000);
}
catch
{
Console.WriteLine("创建监听端口失败");
return;
}
listener.Start(); while (true)
{
Console.WriteLine("start....");
Socket s = listener.AcceptSocket();
NetworkStream ns = new NetworkStream(s);
StreamReader sr = new StreamReader(ns);
String command = sr.ReadLine();
Console.WriteLine("RECIVED MSG:" + command);
String sendmsg = command;
Byte[] sendBytes = System.Text.Encoding.ASCII.GetBytes(sendmsg);
s.Send(sendBytes); //发送空行表示信息传送完毕
String blank = "\r\n
sendBytes = System.Text.Encoding.ASCII.GetBytes(blank.ToCharArray());
s.Send(sendBytes);
}
}
}
} 客户端: using System;
using System.IO;
using System.Net.Sockets;
namespace QTCPClient1
{
class QClient1
{
[STAThread]
public static void Main(string[] args)
{
Console.WriteLine("Connecting to 127.0.0.1:60000");
NetworkStream outStream;
StreamReader inStream;
TcpClient client;
try
{
client = new TcpClient("127.0.0.1",60000);
}
catch(Exception ee)
{
Console.WriteLine("连接服务器失败");
return;
}
outStream = client.GetStream();
inStream = new StreamReader(outStream);
Console.WriteLine("Connected...");
string command = "hello";//传送的命令
Console.WriteLine(command);
Byte[] bytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
outStream.Write(bytes,0, bytes.Length);
Console.WriteLine("服务器返回结果:");
string recMsg;
while (true)
{
recMsg = inStream.ReadLine();
if (recMsg.Equals("\r\n")) break
Console.WriteLine(recMsg);
}
Console.WriteLine("Closing Connectiion...");
client.Close();
Console.ReadLine();
}
}
} 希望服务器端把客户端传递过来的信息原封不动返回给客户端。整个程序本地测试,可以联接,但没有办法传递和接收信息,向高手请教为什么?
解决方案 »
- datatable的load方法的问题
- net2.0升级到net4.0后,出现PInvoke错误
- 安装vs2010问题,求解决,谢谢啦
- 在datalist怎么找不到radio控件的id
- 求助!!!为什么Update不了Oracle数据库
- 困惑----使用委托的优点
- 用vfp做的一个com ,regsvr32 一个com以后,如何在.net中使用它
- 如何获得自己定制的ListView中的ListViewItem的一个事例的物理路径全称
- 当我按下"alt+空格"时,explore.exe窗口要隐藏,再按一下,再显示出来
- 请问谁有用mouse画直线的例子? C#的
- 菜鸟,求助 重构——提取接口的错误
- ===关于GridView数据导入Excel问题求教===
try
{
so.Connect(_ServerAddress);
if (so.Connected)
so.Send(Encoding.UTF8.GetBytes(_Message));
else
so.Close();
}
finally
{
so.Close();
}我都是这么发消息的...
string command = "hello";//传送的命令
Console.WriteLine(command);
Byte[] bytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
outStream.Write(bytes,0, bytes.Length);
你的换行符哪里去了??
因为你在服务器端是:String command = sr.ReadLine();
没有换行符,这行代码不返回!!解决办法:
在客户端:string command = "hello"+"\r\n";//传送的命令