3,405
社区成员
发帖
与我相关
我的任务
分享
package cn.itcast.chapter11;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class test3 extends JFrame implements ActionListener,WindowListener{
static final int PORT=6699;//定义服务端的端口号
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕尺寸使窗口居中
JTextArea area=new JTextArea();
JTextField tfield=new JTextField(45);
JButton but=new JButton("确定");
JPanel panel=new JPanel();
JLabel label=new JLabel("信息");
static ServerSocket server;
static Socket client;
static {//静态代码块,先实例化serversocket并得到socket
try {
server=new ServerSocket(PORT);
client=server.accept();
}catch(Exception e) {
e.printStackTrace();
}
}
test3(){//构造函数,设置界面
setSize(640,420);
setLocation(screen.width/2-320,screen.height/2-210);
area.setLineWrap(true);
setTitle("服务端");
area.setEditable(false);
panel.add(label);
panel.add(tfield);
panel.add(but);
add(area,BorderLayout.CENTER);
add(panel,BorderLayout.SOUTH);
but.addActionListener(this);
tfield.addActionListener(this);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {//按确定时发信息给服务端并显示在文本域中
String receiveMsg;
String sendMsg;
sendMsg=tfield.getText();
try {
//server=new ServerSocket(PORT);
//Socket client=server.accept();
//DataInputStream dis=new DataInputStream(client.getInputStream());
DataOutputStream dos=new DataOutputStream(client.getOutputStream());
if(sendMsg!="") {
String atext=area.getText();
String ftext=tfield.getText()+"\r\n";
area.setText(atext+ftext);
dos.writeUTF(tfield.getText());
}
/*receiveMsg=dis.readUTF();
if(receiveMsg!="") {
area.setText(receiveMsg);
}
//close(client);*/
}catch(Exception IO) {
IO.printStackTrace();
}
tfield.setText("");
}
public void receiveMsg() {//收信息函数,当有信息是显示在文本域中
String reMsg,Msg;
Msg=area.getText();
try {
InputStream is=client.getInputStream();
DataInputStream dis=new DataInputStream(is);
reMsg="接受到信息:"+dis.readUTF()+"\r\n";
if(reMsg!="") {
area.setText(Msg+reMsg);
}
is.close();
}catch(Exception e) {
e.printStackTrace();
}
}
public void windowClosing(WindowEvent e) {//关闭窗口时关闭socket
try {
client.close();
server.close();
}catch(Exception e1) {
e1.printStackTrace();
}
Window window=e.getWindow();
window.dispose();
}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
/*public void close(Socket client)throws Exception {
client.getOutputStream().close();
client.getInputStream().close();
client.close();
}*/
public static void main(String[] args) {//主函数,实例化自己,调用收信息函数收信息
test3 test=new test3();
test.receiveMsg();
}
}