【发布时间】:2014-12-19 13:18:24
【问题描述】:
TCP/IP 套接字程序客户端发送文本服务器接收和存储数据库表。我正在纠正下面的代码,但我有错误文本重新审核时间。
这是客户端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.IO;
namespace ClientApplication
{
class Client
{
static void Main(string[] args)
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
//tcpclnt.Connect("162.144.85.232", 8080);
tcpclnt.Connect("162.144.85.232", 4489);
Console.WriteLine("Connected");
Console.Write("Enter the string to be Sent : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
System.Net.ServicePointManager.Expect100Continue = false;
Console.WriteLine("Sending.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
Console.ReadLine();
tcpclnt.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadLine();
}
}
}
}
这是服务器端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ServerApplication
{
class Server
{
static void Main(string[] args)
{
try
{
IPAddress ipadd = IPAddress.Parse("192.168.1.7");
TcpListener list = new TcpListener(ipadd, 8080);
list.Start();
Console.WriteLine("The server is running at port 8080...");
Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
System.Net.ServicePointManager.Expect100Continue = false;
Socket s = list.AcceptSocket();
Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recived...");
for (int i = 0; i < k; i++)
Console.WriteLine(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The String Was Recived throw Server"));
Console.WriteLine("\n Sent Acknowlegment");
s.Close();
list.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
我正在尝试执行此代码,但发生了这样的错误 无法从传输连接读取数据:现有连接被远程主机强行关闭。请解决我的问题。
【问题讨论】:
-
什么是异常消息?
-
Hii CodeCaster 这是我的错误消息。System.dll 中发生了“System.IO.IOException”类型的未处理异常 谢谢
-
您需要提供更多信息。异常包含此信息。请尝试调试问题。什么是内部异常?此外,当您收到
IOException时,您的代码会捕获SocketException,这在SocketException的继承链中不存在。 -
无法从传输连接读取数据:从客户端向服务器发送文本时,远程主机强制关闭了现有连接
-
您的
while (true)没有意义,试图将多个NetworkStreams 包装在同一个套接字周围。也许这不是 this 问题的原因,那么它将是下一个问题的原因。
标签: c# sockets client-server tcp-ip