我创建了一个本地服务器和一个客户端窗口,以使它们在本地相互通信。
服务器和客户端都已创建。我的问题是我需要客户在
JTextField 我想将它传递给服务器。现在,当我检查输入的字符串时,它会显示
该字符串具有 NULL 值。
这是我的客户代码:
import java.io.*;
import java.net.Socket;
import java.awt.event.*;
import javax.swing.*;
public class MyClientSide extends JFrame{
public static String userFile;
public static String entered = "";
public static String host = "localhost";
public static int port = 8080;
public static Socket socket = null;
public static DataOutputStream out = null;
public MyClientSide(){
JLabel jlbl = new JLabel("File Name: ");
final JTextField jtxt = new JTextField(20);
JButton jbtn = new JButton("Upload to Server");
JPanel jpnl = new JPanel();
jbtn.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {//Start of actionPerformed
entered = jtxt.getText();
}
});
jpnl.add(jlbl);
jpnl.add(jtxt);
jpnl.add(jbtn);
this.add(jpnl);
}
public MyClientSide(String error) {
// TODO Auto-generated constructor stub
JLabel jlbl = new JLabel("Please connect to server");
this.add(jlbl);
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String error = "Please connect to server";
MyClientSide connectFrm = new MyClientSide();
MyClientSide errorFrm = new MyClientSide(error);
try {
socket = new Socket(host,port);
connectFrm.setTitle("File Transfer Client");
connectFrm.setSize(500,80);
connectFrm.setVisible(true);
connectFrm.setDefaultCloseOperation(EXIT_ON_CLOSE);
InputStreamReader(socket.getInputStream()));
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(entered); /*Here is my problem. when I pass this to the server,
The value is NULL. I need to pass a string from
JTextField*/
}
catch (IOException e) {
errorFrm.setTitle("Error!!!!");
errorFrm.setSize(200,100);
errorFrm.setVisible(true);
errorFrm.setDefaultCloseOperation(EXIT_ON_CLOSE);
System.err.print("Please connect to server");
}
}
}
谢谢您的帮助