我正在尝试使用GUI组件实现聊天服务器。我实现了3个部分(服务器,客户端和GUI组件)。
以下是我遇到的一些问题 -
代码:
第一个GUI组件:
public class ChatServer extends javax.swing.JFrame {
String str;
public ChatServer() {
initComponents();
screen.setEditable(false);
}
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
str = enter.getText();
enter.setText("");
screen.append(str+"\n");
}
public static void main(String args[]) {
new ChatServer().setVisible(true);
}
private javax.swing.JTextPane enter;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea screen;
private javax.swing.JButton send;
}
看起来像:
这是我的服务器代码:
public class Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(23);
System.out.println(InetAddress.getLocalHost()+" hazir");
while(true){
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostName() + " baglandi");
new ServerPart(s).start();
}
}
}
public class ServerPart extends Thread {
private Socket s;
public ServerPart(Socket s){
this.s=s;
}
@Override
public void run() {
try {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("Hello" + s.getInetAddress().getHostName());
String gelen;
while(true){
Scanner sc = new Scanner(s.getInputStream());
gelen = sc.nextLine();
if(gelen.trim().equalsIgnoreCase("bye"))
break;
System.out.println("Client: " + gelen);
BufferedReader input = new BufferedReader(
new InputStreamReader(System.in) );
ps.println("Server: " + input.readLine());
}
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户代码:
public class Client extends Thread {
private Socket s;
public Client(Socket s){
this.s=s;
}
@Override
public void run() {
try {
PrintStream ps = new PrintStream(s.getOutputStream());
Scanner sc = new Scanner(s.getInputStream());
ps.println("Hello" + s.getInetAddress().getHostName());
String gelen;
while(true){
BufferedReader input = new BufferedReader(
new InputStreamReader(System.in) );
gelen = sc.nextLine();
if(gelen.trim().equalsIgnoreCase("bye"))
break;
System.out.println("Client: " + gelen);
ps.println("Server: " + input.readLine());
}
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("192.168.1.173", 23);
new Client(s);
}
}
如果你能帮我配偶,我将不胜感激。
答案 0 :(得分:1)
您正在使用PrintStream
类,方法ps.readline();
。如果您正在开发一个聊天应用程序,那么这种方法将不起作用,因为readline方法在找到换行符或文件结束时,或者当回车符即输入时终止流。所以我更喜欢使用.. datainputstream和dataoutputstream -
Socket sc = new Socket("address",port);
DataOutputStream daos;
DataInputStream dis;
dis = new DataInputStream(sc.getInputStream());
daos= new DataOutputStream(sc.getOutputStream());