如何控制从一个单独的方法PrintWriter的?

问题描述 投票:-2回答:1

进出口工作建设,从平板会谈我的电脑我自己的GUI程序。我已经在服务器端在Java中这样做,但我的问题是在客户端。

我想从一个单独的方法将数据发送出的PrintWriter到服务器。我已经在下面的代码来完成的发送(发送“A”),但我不能找出如何从一个单独的方法发送。我相信它,即时通讯不理解一个基本的Java范围的问题。我会很感激的帮助。

我曾尝试变量移动到其他领域。

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

public class TestClient {

    public static void main(String[] args) {
        String hostName = "192.168.0.3";
        int portNumber = 6666;

        try (   //Connect to server on chosen port.
                Socket connectedSocket = new Socket(hostName, portNumber);
                //Create a printWriter so send data to server.
                PrintWriter dataOut = new PrintWriter(connectedSocket.getOutputStream(), true);

                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
            ) {
            //Send data to server.
            dataOut.println("a");

        }catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }

    public static void sendToServer() {
        //I want to control the print writer from this method.
        //I have failed i all the ways i have tried.

    }
}
java socket.io
1个回答
0
投票

你可以移动打印机码(试试块)到sendToServer法,并通过调用它

TestClient client = new TestClient();
client.sendToServer("this is a test");

当然sendToServer方法需要接受一个参数即可。更妙的很可能是把主要方法为入门级,并从您用于发送数据的客户端级分离它。

© www.soinside.com 2019 - 2024. All rights reserved.