2
我想寫一個小型客戶端服務器程序。服務器使用C#,客戶端使用Java。 這裏是代碼:C#服務器和Java客戶端
服務器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Server
{
class Program
{
private TcpListener tcpListener;
public static void Main(string[] args)
{
Program program = new Program();
program.StartServer();
while (true) ;
}
private bool StartServer()
{
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
tcpListener = new TcpListener(ipAddress, 5678);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.ProcessEvents), tcpListener);
Console.WriteLine("Listing at Port {0}.", 5678);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
return true;
}
private void ProcessEvents(IAsyncResult asyn)
{
try
{
TcpListener processListen = (TcpListener)asyn.AsyncState;
TcpClient tcpClient = processListen.EndAcceptTcpClient(asyn);
NetworkStream myStream = tcpClient.GetStream();
if (myStream.CanRead)
{
StreamReader readerStream = new StreamReader(myStream);
string myMessage = readerStream.ReadToEnd();
readerStream.Close();
}
myStream.Close();
tcpClient.Close();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.ProcessEvents), tcpListener);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
客戶:
import java.io.PrintWriter;
import java.net.Socket;
public class Program {
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket("127.0.0.1", 5678);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print("Hello world");
writer.flush();
writer.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
但是當我嘗試創建客戶端的Socket,我得到這個異常:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Program.main(Program.java:10)
任何人都可以告訴我我在做什麼錯嗎?我正在運行x64的Windows 7旗艦版,我沒有看到任何防火牆消息彈出(我曾看到它的服務器一次,我允許並設置爲始終允許)。我可以使用遠程網絡連接,沒有問題。請任何其他建議。
雖然它很高興地看到代碼和客戶端的結果,可以提供更多的背景? Java客戶端說連接被拒絕,服務器是否說它正在監聽?在服務器偵聽的情況下,您可以telnet到該端口,並驗證您沒有得到拒絕連接嗎? –
它可能是Windows防火牆阻止它? –
嘗試先連接telnet,一旦連接任何你輸入的內容都應該打印出來。不過,我懷疑(我還沒有嘗試過),一旦檢測到新行,你的服務器就會掛斷。 如果你可以連接telnet,那麼你可以相當肯定你的問題在於代碼在任何一方。如果沒有,那麼你的問題在於(防火牆?通常是)。如果在Windows上運行,請注意窗口彈出以允許您的程序訪問網絡。有時它往往會隱藏在另一個窗口(您的IDE)後面。 – Newtopian