I using swing(GUI for java).
This is ActionListener
- @Override
- if(e.getSource()==btnServerOpen){
- if(!getPort.isEmpty()){
- portOpen(port);
- }else{
- commText.setText("Not found PORT number");
- }
- }else if(e.getSource()==btnServerClose){
- portClose();
- }else if(e.getSource()==btnClear){
- commText.setText("");
- }
- }
There are server open, server close and text clear.
This is server port open method.
- private void portOpen(int port) {
- disconnected=false;
- try {
- server.start();
- commText.setText("Waiting for connection.");
- e.printStackTrace();
- }
- }
And this is server port close method.
- private void portClose() {
- try {
- disconnected=true;
- ss.close();
- server.interrupt();
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- commText.setText("server is closed");
- }
And this is socket comm thread
- while(!serverSWT.disconnected){
- try{
- client=server.accept();
- ip=client.getRemoteSocketAddress();
- serverSWT.commText.setText(serverSWT.commText.getText()+"\n"+ip+" is connected");
- is=client.getInputStream();
- os=client.getOutputStream();
- byte[] buffer=new byte[100];
- int length;
- while(((length=is.read(buffer))!=-1)&&(!serverSWT.disconnected)){
- serverSWT.commText.setText(rcvBuf+"client: "+rcv);
- os.write(buffer, 0,length);
- serverSWT.commText.setText(serverSWT.commText.getText()+"\nserver: "+rcv);
- }
- client.close();
- }
- }
Line 1 disconnected is main java's boolean variable.
This variable is efficient for thread-stop.
If you don't use the variable, server receive packet one time.
No comments:
Post a Comment