如何从不同的文件(多线程Java套接字编程)访问名为“numberPart”的字符串

时间:2017-05-26 02:04:09

标签: java multithreading sockets

在名为numberPart的线程类中有一个名为ServerRecieve的字符串。调用.start()的位置位于名为Server的其他类中。

'numberPart'最终将用作稍后进行文件传输的端口。

我的问题是:如何访问名为numberPart的类中的Server变量?

运行代码的屏幕截图(左窗口的服务器,右侧的客户端):

server on left window, client on the right

在屏幕截图(服务器)的左侧窗口中,您可以看到右侧窗口的命令行参数的第一个端口号,即通过文本消息发送的4021,并且服务器成功接收到它消息"File transfer port found: 4021"。不幸的是,这个变量位于不同的类中。我想知道如何在名为Server的类中访问该变量。

ServerRecieve代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ServerRecieve extends Thread
{

    Socket servSocket;
    boolean m_bRunThread = true; 
    boolean ServerOn = true;

    public ServerRecieve(Socket s) 
    { 
        super(); 
        servSocket = s;
    } 
    public void run()
    {
        while(true)
        {
            try
            {
                BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
                String fromClient = readFromClient.readLine();
                String a = fromClient;
                int i;
                for(i = 0; i < a.length(); i++)
                {
                    char c = a.charAt(i);
                    if( '0' <= c && c <= '9' )
                    {
                        break;
                    }
                }
                String alphaPart = a.substring(0, i);
                String numberPart = a.substring(i);
                System.out.println("Recieved from client: " + alphaPart +"\n");

                System.out.println("File transfer port found: " + numberPart + "\n");
                //String[] filePortNumber = null;
                //filePortNumber[0] = numberPart;
               // Server thing = new Server(filePortNumber);
                if(fromClient.equals(null))
                {
                    System.exit(0);
                }
                OutputOptions();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {

            }
        }
    }

    void OutputOptions()
    {
        System.out.println("Enter an option ('m', 'f', 'x'): ");
        System.out.println("(M)essage (send)");
        System.out.println("(F)ile (request) ");
        System.out.println("e(X)it ");
    }
}

服务器来源:

import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class Server
{
    private String[] serverArgs;
    public Socket socket;
    public Socket fileSocket;
    public boolean keepRunning = true;
    public int ConnectOnce = 0;
    public String option = "";
    public boolean isConnected = false;
    public String FILE_TO_SEND = "/Users/nanettegormley/Documents/workspace/assignment2/src/servers/cdm.jpg";

    public Server(String[] args) throws IOException 
    {
        // set the instance variable

        this.serverArgs = args;
        if(ConnectOnce == 0)
        {
            int port_number1 = Integer.valueOf(serverArgs[1]);
            ServerSocket serverSocket = new ServerSocket(port_number1);
            socket = serverSocket.accept(); 
            ConnectOnce = 4;
            isConnected = true;

        }

    }
    public String[] serverRun2(String[] args) throws IOException 
    {

        serverArgs = args;
        serverArgs = Arrays.copyOf(args, args.length);
        serverSend.start();
        return serverArgs;
    }

    Thread serverSend = new Thread()
    {
        public void run()
        {   
            OutputOptions();
            while(isConnected)
            {
                try 
                {
                    ServerRecieve serverThread = new ServerRecieve(socket);
                    serverThread.start(); 


                   // input the message from standard input
                   BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));

                   option = input2.readLine(); 
                   if(option.equals("m") || option.equals("M"))
                   {
                        StandardOutput();
                   }
                   if(option.equals("f") || option.equals("F"))
                   {
                       FileTransferSend();
                   }
                   if(option.equals("x") || option.equals("X"))
                   {
                       System.exit(0);

                   }

               }
               catch ( Exception e )
               {
                   System.out.println( e.getMessage() );
               }
            }
        }
    };


public void StandardOutput()
{
        try
        {           
            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            //creating message to send from standard input
            String newmessage = "";
            try 
            {
                System.out.println("Enter your message: ");
                // input the message from standard input
                BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
                String line = "";

                line= input2.readLine(); 
                newmessage += line + " ";

            }
            catch ( Exception e )
            {
                System.out.println( e.getMessage() );
            }
            String sendMessage = newmessage;
            bw.write(sendMessage + "\n");
            bw.newLine();
            bw.flush();
            System.out.println("Message sent to client: "+sendMessage);
            StandardInput();
            //run();
            } 
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {

            }

}
void FileTransferSend()
{
    //connect to the filetransfer



    try
    {   
        System.out.println("Which file do you want? ");
        Scanner scanner = new Scanner(System.in);
        String filename = scanner.nextLine();
        FileInputStream fis = new FileInputStream(new File(filename));
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fileSocket.getOutputStream()));
        int element;
        while((element = fis.read()) !=1)
        {
            dos.write(element);
        }
        byte[] byteBuffer = new byte[1024]; // buffer

        while(fis.read(byteBuffer)!= -1)
        {
            dos.write(byteBuffer);
        }
        OutputOptions();


       // dos.close();
       // fis.close();
    } 
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {

    }
}

void OutputOptions()
{
    System.out.println("Enter an option ('m', 'f', 'x'): ");
    System.out.println("(M)essage (send)");
    System.out.println("(F)ile (request) ");
    System.out.println("e(X)it ");
}


public void StandardInput()
{
    OutputOptions();
    while(true)
    {

        try 
        {
           // input the message from standard input
           BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
           String line2 = "";

           option= input2.readLine(); 
           if(option.equals("m") || option.equals("M"))
           {
               StandardOutput();
           }
           if(option.equals("f") || option.equals("F"))
           {
               FileTransferSend();
           }
           if(option.equals("x") || option.equals("X"))
           {
               System.exit(0);

           }

       }
       catch ( Exception e )
       {
           System.out.println( e.getMessage() );
       }
        finally
        {

        }
    }

}




}

包含所有文件的完整代码:

https://www.dropbox.com/s/0yq47gapsd3dgjp/folder33.zip?dl=0

我的问题是:我可以对允许我在numberPart内访问Server的代码进行哪些更改?

编辑:有没有办法可以提出一个没有得到任何答案的问题,或者我应该删除这个问题并将其重新发布到某个地方?

1 个答案:

答案 0 :(得分:1)

我认为您可以使用侦听器或回调模式来解决此问题。

(因为我正在做C#所以我失去了我的Java记忆所以请耐心等待..)

interface PortAssignable {
  public assignPort(int port);
}

然后让Server类实现该接口

public Server implements PortAssignable {
...
}

和ServerReceive

// Constructor
public ServerRecieve(Socket s, PortAssignable portNotifyListener) {
  _portNotifyListener = portNotifyListener;
  ... your other code ...
}

确保在创建ServerReceive的实例时,通过Server传递this个实例。

ServerRecieve serverThread = new ServerRecieve(socket, this);

现在,当您获得numberPart时,您的下一行可能是

_portNotifyListener.assignPort(numberPart);

您如何选择在assignPort课程中实施Server方法取决于您。

P.S。 我在/r/programming看到了这个问题。