62,620
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ChatServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(7777);
while (true) {
Socket s = ss.accept();
System.out.println("a new client connected!");
final DataInputStream dis = new DataInputStream(s.getInputStream());
new Thread(new Runnable() {//多线程,支持多个客户端
public void run() {
String s1 = "";
try {
while ((s1 = dis.readUTF()) != null) {
System.out.println(s1);
////
////
}
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("断开连接");
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatClient extends Frame {
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Socket s = null;
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
this.setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try {
if(s!=null)
s.close();
} catch (IOException ex) {
}
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
}
private void connect() {
try {
/*Socket 这里的问题*/ s = new Socket("127.0.0.1", 7777);
System.out.println("connected!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//String s2 = taContent.getText();
taContent.setText(str);
tfTxt.setText("");
try {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
dos.flush();
//dos.close();//////////////////////
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}