我正在尝试做一个简单的 Gmail 客户端。问题是我得到了一个非常奇怪的回应。实际上我根本没有得到回应SslStream.read
。首先,当我作为客户端连接到 gmail 服务器时,它可以正常工作(Connect()
方法),但是当我尝试从电子邮件中获取号码时,再次使用SslStream.read
withleerMensaje()
方法时,它变得很奇怪并且停止运行,并且网页卡住了加载。
这是我正在学习的课程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
using System.Net.Mail;
namespace GmailClient
{
public class GmailPop
{
private SslStream sslStream;
private String user;
private String pass;
public GmailPop(String user, String pass)
{
this.user = user;
this.pass = pass;
}
public bool Connect()
{
String response;
byte[] buffer = new byte[2048];
int bytes = -1;
TcpClient server = new TcpClient("pop.gmail.com", 995);
sslStream = new SslStream(server.GetStream());
sslStream.AuthenticateAsClient("pop.gmail.com");
bytes = sslStream.Read(buffer, 0, buffer.Length);
response = Encoding.ASCII.GetString(buffer,0,bytes);
sslStream.Write(Encoding.ASCII.GetBytes("USER recent:" + user+"\r\n"));
bytes = sslStream.Read(buffer, 0, buffer.Length);
response = Encoding.ASCII.GetString(buffer,0,bytes);
if(response.StartsWith("+OK")){
sslStream.Write(Encoding.ASCII.GetBytes("PASS "+pass+"\r\n"));
bytes = sslStream.Read(buffer,0,buffer.Length);
response = Encoding.ASCII.GetString(buffer, 0, bytes);
return response.StartsWith("+OK");
}
return false;
}
public int numCorreos()
{
String res = escribirLeer("STAT");
String[] resA = res.Split(' ');
int num = Int32.Parse(resA[1]);
return num;
}
public String leerMensaje()
{
int bytes = -1;
byte[] buffer = new byte[2048];
String msg = "";
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
msg += Encoding.ASCII.GetString(buffer, 0, bytes);
} while (bytes != 0);
return msg;
}
public void escribirMsg(String msg)
{
byte[] buffer = Encoding.ASCII.GetBytes(msg);
sslStream.Write(buffer);
sslStream.Flush();
}
public String escribirLeer(String msg)
{
escribirMsg(msg);
String respuesta = leerMensaje();
return respuesta;
}
}
}
这是调用该方法的aspx网页:
GmailPop client;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null && Session["pass"] != null)
{
String user = Session["user"].ToString();
String pass = Session["pass"].ToString();
client = new GmailPop(user, pass);
if (client.Connect())
{
Session["active"] = true;
Response.Write(numCorreos());
}
else
{
Session.Remove("pass");
Response.Redirect("login.aspx?error=login");
}
}
else
{
Response.Redirect("login.aspx");
}
}
}