编写一个聊天程序后,是不是一定要个服务器?(很菜的问题)
如果你希望程序能自动获取到对方IP的话使用服务器是比较科学的。当然还可以让程序固定将听某一端口,在其他人启动程序后就扫描网段内的全部机器就能确认哪些机器安装了你的聊天程序了(很笨的办法)。
服务器端(注意要先启动服务器端)
import javaio;
import javanet;
import javaawt;
import javaawtevent;
public class server extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
ServerSocket server;
Socket client;
InputStream in;
OutputStream out;
public server() {
super("服务器");
setSize(250, 250);
paneladd(label);
paneladd(tf);
tfaddActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Systemexit(0);
}
});
show();
try {
server = new ServerSocket(4000);
client = serveraccept();
taappend("客户机是:" + clientgetInetAddress()getHostName() + "\n\n");
in =clientgetInputStream();
out= clientgetOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
inread(buf);
String str = new String(buf);
taappend("客户机说:" + str + "\n\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tfgetText();
byte[] buf = strgetBytes();
tfsetText(null);
outwrite(buf);
taappend("我说:" + str + "\n");
} catch (IOException ioe) {
}
}
public static void main(String[] args) {
new server();
}
}
客户端
import javaio;
import javanet;
import javaawt;
import javaawtevent;
public class client extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
Socket client;
InputStream in;
OutputStream out;
public client() {
super("客户机");
setSize(250, 250);
paneladd(label);
paneladd(tf);
tfaddActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Systemexit(0);
}
});
show();
try {
client = new Socket(InetAddressgetLocalHost(), 4000);
taappend("服务器是:" + clientgetInetAddress()getHostName() + "\n\n");
in = clientgetInputStream();
out = clientgetOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
inread(buf);
String str = new String(buf);
taappend("服务器说:" + str + "\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tfgetText();
byte[] buf = strgetBytes();
tfsetText(null);
outwrite(buf);
taappend("我说:" + str + "\n");
} catch (IOException iOE) {
}
}
public static void main(String args[]) {
new client();
}
}
这个只能在自己一台电脑上先启动服务器再启动客户端才行,要想一台机子启动服务器端一台机子启动客户端需要把客户端的 client = new Socket(InetAddressgetLocalHost(), 4000);改成 client = new Socket("服务器Ip", 4000);(前提是两台机子连在局域网里面的)
0条评论