在java中制作服务器/客户端聊天程序时出现连接错误

时间:2015-04-24 23:17:45

标签: java sockets client server

我没有完成这个项目,但我只是想确保一切正常,更具体地说是客户端和服务器正在连接,而且我遇到了连接错误。这是我的两个程序。我也不完全确定如何在日食中同时运行它们,所以也许这就是问题所在。非常感谢任何帮助

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

public class Server {



public  void main(String[] args)throws Exception {

    ServerSocket server = new ServerSocket(3333);;

    while (true)
    {
        Socket clientsocket = server.accept();
        Scanner sc = new Scanner(clientsocket.getInputStream());
        PrintStream p = new PrintStream(clientsocket.getOutputStream());
        String message = "Hello from server";
        p.print(message);
    }

}

而客户

    public static void main(String[] args)throws Exception {
    Client display = new Client();
    display.setVisible(true);

    try {
    Socket server = new Socket("localhost", 3333);
    Scanner sc = new Scanner(server.getInputStream());
    PrintStream p = new PrintStream(server.getOutputStream());
    System.out.println(sc.next());

    server.close();
    sc.close();
    p.close();


    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

我在客户端上方和下方都有一些我没有展示的gui东西。当我运行这些时,我得到以下错误

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 Client.main(Client.java:56)

和第56行是 - Socket server = new Socket(&#34; localhost&#34;,3333);

0 个答案:

没有答案