这是我第一次进行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
谢谢,现在我已经改变了端口,它显示了一条新消息,但只是第一次,所以程序显示每个端口一条消息我有什么需要改变我的代码来解决这个问题? –