【发布时间】:2013-01-16 10:39:17
【问题描述】:
我在 vmware 中运行了 Ubuntu 11.10。我在 Ubuntu 中运行 Java tcp 服务器。因此,当我将此服务器与来自 Ubuntu 的客户端连接时,它工作正常。但是当我试图从另一个操作系统(Windows 7)连接这个服务器时,它显示连接错误。我尝试连接 java 和 C# 客户端,但两次都显示连接错误。这是错误消息:
System.Net.Sockets.SocketException:无法建立连接,因为目标机器主动拒绝它 192.168.0.129:20000 在 System.Net.Sockets.Socket.DoConnect(端点 endPointSnapshot,SocketAddress socketAddress) 在 System.Net.Sockets.Socket.Connect(端点 remoteEP) 在 TestUbuntuSocket.Form1.button1_Click(对象发送者,EventArgs e) 在 System.Windows.Forms.Control.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs 事件) 在 System.Windows.Forms.Control.WmMouseUp(消息和 m,MouseButtons 按钮,Int32 点击) 在 System.Windows.Forms.Control.WndProc(消息和 m) 在 System.Windows.Forms.ButtonBase.WndProc(消息和 m) 在 System.Windows.Forms.Button.WndProc(消息和 m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息和 m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
这是我的 C# 客户端 Socket 代码:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)));
if (s.Connected)
{
s.Send(Encoding.ASCII.GetBytes(textBox3.Text));
}
else
MessageBox.Show("Not Connected");
这是我的 Java 客户端套接字代码:
Socket socket = null;
try{
socket = new Socket(txtIp.getText(), Integer.parseInt(txtPort.getText()));
}
catch(Exception exc){
JOptionPane.showMessageDialog(this, "Server is not available!!");
return;
}
try{
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
out.println(txtMessage.getText());
socket.close();
}
catch(Exception exc){
JOptionPane.showMessageDialog(this, "Error when sending data!!");
}
服务器 Java 代码:
ServerSocket s = new ServerSocket(port);
while (start)
{
Socket incoming = s.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
String message = "";
String line = in.readLine();
while(line != null){
message += line;
line = in.readLine();
}
JOptionPane.showMessageDialog(null, message);
}
这是'sudo netstat -atnp'的输出:
Proto Recv-Q Send-Q 本地地址 外部地址 状态 PID/程序名称 tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 408/sshd
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 925/cupsd
tcp6 0 0 ::1:42098 :::* LISTEN 2168/java
tcp6 0 0 :::22 :::* LISTEN 408/sshd
tcp6 0 0 ::1:631 :::* 听 925/cupsd
tcp6 0 0 :::20000 :::* LISTEN 3015/java
tcp6 0 0 127.0.0.1:20000 127.0.0.1:56269 CLOSE_WAIT 3015/java
那我错了吗?
【问题讨论】:
-
您能否将屏幕截图替换为文本中的完整错误消息?
-
防火墙设置?我猜该端口已关闭以供非本地访问。
-
Java 代码有什么异常?
-
@Fildor 我在运行应用程序之前打开了端口。我的命令是:sudo ufw allow 20000
-
@Eng.Fouad java.net.ConnectException:连接被拒绝:连接
标签: c# java sockets ubuntu ubuntu-11.04