package three_part;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ServerUI extends JFrame{ //界面类
JTextArea mainArea;
JTextArea sendArea;
SvrCom server;
public ServerUI(){
super("服务器端");
Container contain =getContentPane();
contain.setLayout(new BorderLayout());
mainArea = new JTextArea();
JScrollPane mainAreaP= new JScrollPane(mainArea);
JPanel panel =new JPanel(new BorderLayout());
sendArea =new JTextArea(3,8);
JButton sendBtn = new JButton("发送");
sendBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
server.sendMsg(sendArea.getText());
mainArea.append("【服务器】"+sendArea.getText()+"\n");
sendArea.setText("");
}
});
JPanel tmpPanel=new JPanel();
tmpPanel.add(sendBtn);
panel.add(tmpPanel,BorderLayout.EAST);
panel.add(sendArea,BorderLayout.CENTER);
contain.add(mainAreaP,BorderLayout.CENTER);
contain.add(panel,BorderLayout.SOUTH);
setSize(500,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]agrs){
ServerUI ui= new ServerUI();
SvrCom svrCom= new SvrCom(ui);
}
public void setServer(SvrCom svrCom) {
this.server = svrCom;
}
}
package three_part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SvrCom { //通讯类
Socket client;
ServerSocket soc;
BufferedReader in;
PrintWriter out;
ServerUI ui;
public SvrCom(ServerUI ui) {
this.ui=ui;
ui.setServer(this);
try {
soc = new ServerSocket(8888);
System.out.println("启动");
client= soc.accept();
System.out.println("连接成功");
in=new BufferedReader(new InputStreamReader(client.getInputStream()));
out=new PrintWriter(client.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
String msg="";
while(true){
try {
msg=in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(msg!=null&&msg.trim()!=""){
System.out.println("> >"+msg);
ui.mainArea.append(msg+"\n");
}
}
}
public void sendMsg(String msg){
try{
out.println("[【服务器】"+msg);
}catch(Exception e){
System.out.println(e);
}
}
}
public void setServer(SvrCom svrCom) { this.server = svrCom; }这个是将server实例化吗? 如果不是,加粗下划线得那一段是怎么实现??
2015071819
慕瓜9220888
四无小青年
随时随地看视频慕课网APP
相关分类