连接拒绝了socket的异常。 Java的

时间:2016-11-27 17:54:57

标签: java sockets server client

我一直在关注O'Reilly的Head First书籍,为简单的聊天客户端连接套接字。它给了我一份我在下面发布的例外列表以及该程序。我经历了几次,看不出我出错的地方。谢谢!

import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleChatClientA {

	JTextField outgoing;
	PrintWriter writer;
	Socket sock;

	public void go() {
		JFrame frame = new JFrame("Generation X Chat Client");
		JPanel mainPanel = new JPanel();

		outgoing = new JTextField(20);
		JButton sendButton = new JButton("Send");
		sendButton.addActionListener(new SendButtonListener());
		mainPanel.add(outgoing);
		mainPanel.add(sendButton);
		frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
		setUpNetworking();
		frame.setSize(400, 500);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	public void setUpNetworking() {
		try {
			sock = new Socket("127.0.0.1", 36555);
			writer = new PrintWriter(sock.getOutputStream());
			System.out.println("Network established.");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public class SendButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent a) {
			try {
				writer.println(outgoing.getText());
				writer.flush();
			} catch (Exception ex) {
				ex.printStackTrace();
			}

			outgoing.setText("");
			outgoing.requestFocus();
		}
	}

	public static void main (String[] args) {
		new SimpleChatClientA().go();
	}
}

例外情况如下:

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 SimpleChatClientA.setUpNetworking(SimpleChatClientA.java:32)
    at SimpleChatClientA.go(SimpleChatClientA.java:23)
    at SimpleChatClientA.main(SimpleChatClientA.java:55)

我对服务器有这样的东西,因为它没有在book程序中显示ServerSocket连接。它是否正确?我编译并运行此服务器,然后在命令提示符下编译并运行上面的代码:

import java.io.*;
import java.net.*;

public class TCPServer {
		public static void main (String[] args) {
			try {
				ServerSocket Server = new ServerSocket(5000);
				System.out.println("Waiting for TCP client connection on port 5000.");

				while (true) {
					Socket sock = Server.accept();
					System.out.println("The client has connected successfully.");
				}
			} catch(IOException ex) {
				ex.printStackTrace();
		}
	}
}

0 个答案:

没有答案