Build A Simple Socket Server - Can Be Used To Check The HTTP Protocol

来源:互联网 发布:unity3d简单游戏制作 编辑:程序博客网 时间:2024/04/28 04:02

Build A Simple Socket Server

Used 4h 41mins to write it, ,, which only proved my lack of experience.

import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Font;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import javax.swing.AbstractButton;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import com.sun.xml.internal.bind.CycleRecoverable.Context;public class A_Main {private boolean bIsServed=false;private ServerSocket serverSocket=null;private Socket sAccepted=null;private OutputStream out=null;private InputStream in=null;private F_Layout view=null;public static void main(String[] args) {A_Main a=new A_Main();a.fInit();a.fMain();}private void fInit(){}private void fMain(){view=new F_Layout(this);fInitSocketServer();fSocketServer();}private class F_Layout extends JFrame implements ActionListener{private A_Main context=null;private JFrame jfParent;private int iWidth;private int iHeight;private Container cBody;private JTextArea jtGet;private JTextArea jtOut;private JTextArea jtEdit;private AbstractButton jbSend;private JTextArea jtContext;private JButton jbStart;private JButton jbStop;private JTextArea jtC_Info;public F_Layout(A_Main context){this.context=context;fInit();fMain();}private void fInit(){Dimension screensize=Toolkit.getDefaultToolkit().getScreenSize();iWidth=(int)screensize.getWidth();iHeight=(int)screensize.getHeight();}private void fMain(){jfParent = new JFrame();cBody=jfParent.getContentPane();cBody.setLayout(new BorderLayout());//For TitleJPanel jpTitle=new JPanel(new BorderLayout());JLabel jlTitle=new JLabel("Socket Service");jlTitle.setForeground(Color.pink);jlTitle.setFont(new Font("French Script MT",1,24));jpTitle.add(jlTitle,"Center");//For JPSocketJPanel jpSocket=new JPanel(new BorderLayout());JPanel jpS_Get=new JPanel(new FlowLayout());JLabel jlGet=new JLabel("Input Stream:");jtGet=new JTextArea(12,35);JScrollPane jsGet =new JScrollPane(jtGet);jpS_Get.add(jlGet);jpS_Get.add(jsGet);JPanel jpS_Put=new JPanel(new BorderLayout());JPanel jpS_P_Put=new JPanel(new FlowLayout());JLabel jlPut=new JLabel("Output Stream:");jtOut=new JTextArea(12,35);JScrollPane jsPut =new JScrollPane(jtOut);jpS_P_Put.add(jlPut);jpS_P_Put.add(jsPut);JPanel jpS_P_Send=new JPanel(new FlowLayout());jtEdit=new JTextArea(3,25);JScrollPane jsEdit =new JScrollPane(jtEdit);jbSend=new JButton("Send");jbSend.addActionListener(this);jpS_P_Send.add(jsEdit);jpS_P_Send.add(jbSend);jpS_Put.add(jpS_P_Put,"Center");jpS_Put.add(jpS_P_Send,"South");jpSocket.add(jpS_Get,"North");jpSocket.add(jpS_Put,"Center");//For JPControlJPanel jpControl=new JPanel(new BorderLayout());JPanel jpC_South=new JPanel(new FlowLayout());jbStart=new JButton("Start");jbStop=new JButton("Stop");jbStart.addActionListener(this);jbStop.addActionListener(this);jpC_South.add(jbStart);jpC_South.add(jbStop);JPanel jpC_Context=new JPanel(new BorderLayout());jtContext=new JTextArea(10,25);jtC_Info=new JTextArea(7,25);JScrollPane jsContext =new JScrollPane(jtContext);JScrollPane jsC_Info=new JScrollPane(jtC_Info);jpC_Context.add(jsContext,"Center");jpC_Context.add(jsC_Info,"North");//jpControl.add(new JPanel(),"North");jpControl.add(jpC_Context,"Center");jpControl.add(jpC_South,"South");cBody.add(jlTitle,"North");cBody.add(jpSocket,"Center");cBody.add(jpControl,"East");jfParent.setBounds(iWidth/10*1,iHeight/10*1,iWidth/10*8,iHeight/10*7);jfParent.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//jfParent.setAlwaysOnTop(true);jfParent.setVisible(true);}public void fAddInput(String s){jtGet.append(s);}public void fClearInput(){jtGet.setText("");}public void fAddOutput(String s){try{out.write(s.getBytes("utf-8"));out.flush();jtOut.append(s);} catch (Exception e) {fAlert("fAddOutput(): "+e.toString(),"E");}}public void fClearOutput(){jtOut.setText("");}public void fSetInfo(String s){jtC_Info.setText(s);}@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()==jbSend){if(out!=null){String sEdit=jtEdit.getText();jtEdit.setText("");fAddOutput(sEdit);fAlert("Send Text: "+sEdit);}else{fAlert("out Is Null!");}}else if(e.getSource()==jbStop){context.fStopSocketServer();}else if(e.getSource()==jbStart){context.fStartSocketServer();}else{fAlert("Unknown ID Is Clicked!");}}public void fLog(String ... s){if(s.length==0){}else if(s.length==1){jtContext.append(s[0]);}else if(s.length==2){jtContext.append(s[1]+" => "+s[0]);}jtContext.append("\n**");}}private void fInitSocketServer(){try{serverSocket=new ServerSocket(50001);fAlert("ServerSocket Inited Sucessed!");}catch(Exception e){fAlert("fInitSocketServer():"+e.toString(),"E");}}private void fSocketServer(){    // To Toggle SocketServerif(bIsServed){fStopSocketServer();}else{fStartSocketServer();}}private void fStartSocketServer(){    // Make Changes In UI; Only Used By fSocketServer();if(bIsServed){fAlert("Socket Server Is Already On Service!");return;}bIsServed=true;if(serverSocket!=null){T_SocketListener t=new T_SocketListener();t.start();fAlert("Socket Listener Thread Setup Now!");}else{fAlert("serverSocket Is Null","E");}}private void fStopSocketServer(){    // Make Changes In UI; Only Used By fSocketServer();if(!bIsServed){fAlert("Socket Server Is Already Off Service Now!");return;}bIsServed=false;if(null!=out){try{out.close();fAlert("out closed(): "+(out==null));}catch(Exception e){fAlert("out close(): "+e.toString());}}else{fAlert("out Is NULL!","E");}if(null!=in){try{in.close();fAlert("out closed(): "+(in==null));}catch(Exception e){fAlert("in close(): "+e.toString());}}else{fAlert("in Is NULL!","E");}if(null!=sAccepted){try{sAccepted.close();fAlert("sAccepted closed(): "+(sAccepted==null));}catch(Exception e){fAlert("sAccepted close(): "+e.toString());}}else{fAlert("sAccepted Is NULL!","E");}}private class T_SocketListener extends Thread{public T_SocketListener(){}@Overridepublic void run(){try {serverSocket=new ServerSocket(50000);while(bIsServed){fAlert("Prepared Accpted!");sAccepted=serverSocket.accept();fAlert("Accpted!");view.fClearInput();view.fClearOutput();out=sAccepted.getOutputStream();in=sAccepted.getInputStream();T_SocketReceive tReceive=new T_SocketReceive();tReceive.start();StringBuilder sbInfo=null;//sbInfo.append("Server Socket:\n");//sbInfo.append("InetAddress: \n");//sbInfo.append(serverSocket.getInetAddress()+"\n");////sbInfo.append("HostAddress: \n");////sbInfo.append(serverSocket.getInetAddress().getHostAddress()+"\n");//sbInfo.append("LocalSocketAddress: \n");//sbInfo.append(serverSocket.getLocalSocketAddress()+"\n");//sbInfo.append("Port: \n");//sbInfo.append(serverSocket.getLocalPort()+"\n");//sbInfo.append("\n\n");////sbInfo.append("User Socket:\n");//sbInfo.append("LocalAddress: \n");//sbInfo.append(sAccepted.getLocalAddress()+"\n");//sbInfo.append("HostAddress: \n");//sbInfo.append(sAccepted.getLocalAddress().getHostAddress()+"\n");//sbInfo.append("HostName: \n");//sbInfo.append(sAccepted.getLocalAddress().getHostName()+"\n");//sbInfo.append("Port: ");//sbInfo.append(sAccepted.getPort()+"\n");//view.fSetInfo(sbInfo.toString());//T_SocketServer tServer=new T_SocketServer(sAccepted.getOutputStream());//tServer.start();}}catch (Exception e) {fAlert("Server Accept(): "+e.toString(),"E");}}}private class T_SocketReceive extends Thread{public T_SocketReceive() {}@Overridepublic void run(){try {BufferedReader br=new BufferedReader(new InputStreamReader(in));for(String s;(s=br.readLine())!=null;){view.fAddInput(s+"\n");}}catch(Exception e) {fAlert("in is closed by forse: "+e.toString(),"E");fStopSocketServer();fStartSocketServer();}}}private void fAlert(String ... s){view.fLog(s);}}

   微笑


0 0
原创粉丝点击