간단한 클라이언트와 간단한 서버에 연결할 수 없습니다. 서버를 실행할 때 문제가없는 것 같지만 클라이언트와 데이터를 보내려고하면 시간 초과 기간 내에 연결되지 않았다는 예외가 발생합니다. 여기 .NET의 소켓이 연결되지 않습니다.
내가 사용하고 서버 코드 :public void server()
{
try
{
byte[] bytes = new byte[1024];
int bytesReceived = 0;
String message = "";
IPAddress direction = IPAddress.Parse(getIPExternal()); //getIPExternal return the public IP of the machine in which the programm runs
IPEndPoint directionPort = new IPEndPoint(direction, 5656);
Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(directionPort);
socketServer.Listen(100);
while (true)
{
Socket client = socketServer.Accept();
bytesReceived = client.Receive(bytes);
message = System.Text.Encoding.Unicode.GetString(bytes, 0, bytesReceived);
editMultiline.Invoke(new writeMessageDelegate(writeMessage), new object[] { message, "client"}); //Ignore this, it is just to show the info in a textbox because the server code runs in a diferent thread
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
프로그램이 실행되는 나는 기계에서 공용 IP를 얻을이 방법 : 여기
public string getIPExternal()
{
string direction;
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
direction = stream.ReadToEnd();
stream.Close();
response.Close();
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
을 그리고 내 클라이언트 코드 :
public void client(string directionIP, string message) //directionIP is the IP from the computer to which i want to get connected
{
try
{
byte[] bytesSend = System.Text.Encoding.Unicode.GetBytes(message);
IPAddress direction = IPAddress.Parse(directionIP);
IPEndPoint directionPort = new IPEndPoint(direction, 5656);
Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.Connect(directionPort);
socketClient.Send(bytesSend);
socketClient.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Client error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
어떤 제안이 좋을 것입니다.
어디에서 예외가 발생합니까? – caesay
ex.Message의 표시를 중단 할 것을 권합니다. Ex.ToString()을 대신 사용하십시오. –
@ezgar, 이전에 대답했지만 다른 문제를 다루기 때문에 코드를 테스트 한 후에 삭제했습니다. sniperX가 물었던 것처럼, 예외가 어디서 던져졌으며 예외 메시지는 무엇입니까? 내 설치 프로그램이 'dyndns.org'로 검색 할 공용 IP를 가지고 있지 않아 비슷한 오류를 복제 할 수 없습니다. –