我想编写一个应用程序,学生输入他的姓名、ID、电子邮件、电话号码,然后单击保存按钮,它必须发送到服务器并保存为 file.txt,,,, 我写了这段代码,但是这个每次我在客户端运行“java.net.ConnectException:连接被拒绝:连接”时都会显示错误, 这是我的代码,,,请任何人帮助我??
服务器:
package server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket service;
service = new ServerSocket(1309);
Socket server = service.accept();
System.out.println("server has connected");
InputStreamReader input = new InputStreamReader(server.getInputStream());
DataOutputStream output = new DataOutputStream(server.getOutputStream());
BufferedReader in = new BufferedReader(input);
String inpput = in.readLine();
PrintWriter f = new PrintWriter("student.txt", "UTF-8");
f.println(inpput);
f.close();
service.close();
} catch (IOException e) {
System.out.println(e);
}
}
private static FileWriter FileWriter(String studenttxt) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
客户端:
package project4;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class p4 extends javax.swing.JFrame {
public p4() {
initComponents();}
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
try {
Socket client = new Socket("localhost", 1309);
InputStreamReader input = new InputStreamReader(client.getInputStream());
DataOutputStream output = new DataOutputStream(client.getOutputStream());
BufferedReader in = new BufferedReader(input);
String n, i, e, t;
n = name.getText();
i = id.getText();
e = email.getText();
t = phone.getText();
String mm = n + i + e + t;
output.writeBytes(mm);
output.flush();
System.out.println("save");
output.close();
input.close();
client.close();
} catch (IOException o) {
System.out.println(o);
}}
public static void main(String args[]) {
p4 n = new p4();
n.saveActionPerformed(null);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new p4().setVisible(true);
}
});
}
public javax.swing.JTextField email;
public javax.swing.JTextField id;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
public javax.swing.JTextField name;
public javax.swing.JTextField phone;
protected javax.swing.JButton save; }
最佳答案
代码看起来不错(尽管您会在客户端中收到 NullPointerException
,因为 name
在第 22 行左右仍然为空)。
当我在 Windows 中完成类似的程序时,问题出在防火墙上。 您是否尝试过(暂时)关闭防火墙?
关于java.net.ConnectException : Connection refused: connect ,,客户端/服务器 TCP 套接字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20129743/