這是我第一次進行Socket編程,我做了一個客戶端程序和一個服務器程序,並且服務器只是發送一條簡單的消息給客戶端。 問題是,當我更改消息時,它將再次顯示舊消息。Java服務器總是返回相同的消息
這是客戶
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.util.*;
public class Client extends JFrame {
public static final int PORT = 49998;
Client(){
JFrame window = new JFrame();
JPanel thePanel = new JPanel();
JTextField txt = new JTextField(20);
JButton btn = new JButton("Send");
window.add(thePanel);
thePanel.add(txt);
thePanel.add(btn);
window.setSize(400,400);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setTitle("Client");
window.setVisible(true);
}
public static void main(String[] args){
new Client();
Socket conect;
String ip;
Scanner sc = new Scanner(System.in);
System.out.print("Enter you're IP adress: ");
ip = sc.nextLine();
try{
conect = new Socket(ip,PORT);
BufferedReader read = new BufferedReader(
new InputStreamReader (conect.getInputStream()));
String line = read.readLine();
if(line == null){
System.out.println("Error reading from server");
}
System.out.println();
System.out.println(line);
read.close();
}catch(IOException e){
System.out.println("Can't connect to server");
}
}
}
,這是服務器
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Server {
static PrintWriter pw;
Server(){
JFrame window = new JFrame();
JPanel thePanel = new JPanel();
JTextField txt = new JTextField(20);
JButton btn = new JButton("Send");
window.add(thePanel);
thePanel.add(txt);
thePanel.add(btn);
window.setSize(400,400);
window.setTitle("Server");
window.setVisible(true);
}
public static void main(String[] args){
new Server();
ServerSocket server;
Socket connection;
int port = 49998;
try{
server = new ServerSocket(port);
while(true){
connection = server.accept();
sendMsg(connection);
}
}catch(IOException e){
System.out.println("Problem connection to client");
}
}
public static void sendMsg(Socket con){
try{
pw = new PrintWriter(
con.getOutputStream());
pw.println(" this actually work");
//這是消息,如果我改變這個conten它不會工作了,除非我改變端口 pw.flush(); pw.close(); catch(IOException e){System.out.print(「Error connceting to client」); }}
}
我沒有做的事情的JFrame卻又如此不重視它。
如果你還沒有在JFrame中做過什麼,你爲什麼要發佈它?對於未來的問題,您應該嘗試僅包含相關的代碼。有關更多詳細信息,請參見[mcve]。 – Arc676
'readLine()'返回null不是錯誤。這是一個同行脫節。 – EJP
謝謝,現在我已經改變了端口,它顯示了一條新消息,但只是第一次,所以程序顯示每個端口一條消息我有什麼需要改變我的代碼來解決這個問題? –