Java套接字编程:拒绝连接

时间:2015-01-23 14:38:52

标签: java sockets network-programming lan

我最近一直致力于开发一种在局域网上工作的信使。我已经为服务器和客户端编写了java代码。

Server.java

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

class Server
{   
    private ServerSocket ss;
    private Hashtable outputStreams = new Hashtable();

    public Server( int port ) throws IOException 
    {
        listen( port );
    }

    private void listen( int port ) throws IOException 
    {
        ss = new ServerSocket( port );
        System.out.println( "Listening on "+ss );

    // Keep accepting connections forever
    while (true) 
    {
        // Grab the next incoming connection
        Socket s = ss.accept();

        // Tell the world we've got it
        System.out.println( "Connection from "+s );

        // Create a DataOutputStream for writing data to the other side
        DataOutputStream dout = new DataOutputStream( s.getOutputStream() );

        // Save this stream so we don't need to make it again
        outputStreams.put( s, dout );

        // Create a new thread for this connection, and then forget about it
        new ServerThread( this, s );
    }
}

// Get an enumeration of all the OutputStreams, one for each client connected to us
Enumeration getOutputStreams() 
{
    return outputStreams.elements();
}

// Send a message to all clients (utility routine)
void sendToAll( String message ) 
{
    // We synchronize on this because another thread might be calling removeConnection() and this would screw us up as we tried to walk through the list
    synchronized( outputStreams ) 
    {
        // For each client ...
        for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) 
        {
            // ... get the output stream ...
            DataOutputStream dout = (DataOutputStream)e.nextElement();
            // ... and send the message

            try {
                dout.writeUTF( message );
            } catch( IOException ie ) { System.out.println( ie ); }
        }
    }
}

// Remove a socket, and it's corresponding output stream, from our
// list. This is usually called by a connection thread that has
// discovered that the connectin to the client is dead.
void removeConnection( Socket s ) 
{
    // Synchronize so we don't mess up sendToAll() while it walks
    // down the list of all output streamsa
    synchronized( outputStreams ) 
    {
        // Tell the world
        System.out.println( "Removing connection to "+s );

        // Remove it from our hashtable/list
        outputStreams.remove( s );

        // Make sure it's closed
        try {
            s.close();
        } catch( IOException ie ) {
            System.out.println( "Error closing "+s );
            ie.printStackTrace();
        }
    }
}

// Main routine
static public void main( String args[] ) throws Exception 
{
    // Create a Server object, which will automatically begin accepting connections.
    new Server( 5252 );
}
}

Client.java

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

public class Client extends JFrame implements Runnable
{
// Components for the visual display of the chat windows
private TextField tf = new TextField();
private TextArea ta = new TextArea();

// The socket connecting us to the server
private Socket socket;

// The streams we communicate to the server; these come from the socket
private DataOutputStream dout;
private DataInputStream din;

// Constructor
public Client(String host, int port)
{
    // Set up the screen
    ta.setEditable(false);
    setLayout( new BorderLayout() );
    add( "North", tf );
    add( "Center", ta );

    setSize(200,200);
    setVisible(true);
    // We want to receive messages when someone types a line
    // and hits return, using an anonymous class as
    // a callback
    tf.addActionListener( new ActionListener() {
        public void actionPerformed( ActionEvent e ) {
            tf.setText(" ");
            processMessage( e.getActionCommand() );
        }
    } );

    // Connect to the server
    try {
        // Initiate the connection
        socket = new Socket( host, port );

        // We got a connection! Tell the world
        System.out.println( "connected to "+socket );

        din = new DataInputStream( socket.getInputStream() );
        dout = new DataOutputStream( socket.getOutputStream() );

        // Start a background thread for receiving messages
        new Thread( this ).start();
    } catch( IOException ie ) { System.out.println( ie ); }
}

// Gets called when the user types something
private void processMessage( String message ) 
{
    try {
        // Send it to the server
        dout.writeUTF( message );

        // Clear out text input field
        tf.setText( "" );
    } catch( IOException ie ) { System.out.println( ie ); }
}

// Background thread runs this: show messages from other window
public void run() 
{
    try 
    {
        // Receive messages one-by-one, forever
        while (true) 
        {
            // Get the next message
            String message = din.readUTF();

            // Print it to our text window
            ta.append( message+"\n" );
        }
    } catch( IOException ie ) { System.out.println( ie ); }
}

public static void main(String[] args)
{
    new Client("192.168.29.12",5252);
}
}

这是两个文件,我已经在互联网上检查了每个可能的资源,以确定此代码的有效性,这是正确的。值得关注的是代码在localhost上正常运行,即当我的系统是服务器和客户端时(当主机地址是127.0.0.1时),但是当我在我的系统上运行服务器而在连接到同一LAN的其他系统上运行客户端时因为我的(即主机)客户端窗口表示连接被拒绝,即使服务器正在运行并且我已经删除了所有防火墙设置。 我真的很感谢能够提供帮助的人。我真的无法解决这个问题。我已经尝试了所有可能的解决方案。

顺便说一句,对于互联网我们使用代理服务器。这与局域网连接有什么关系吗?

0 个答案:

没有答案