Socket连接技术

使用Socket 是连接两台计算机最简单的方法,另外由于Socket 使用的是TCP 协议,所以
也就保证了传输的质量。但在这里要注意的是,并不是所有的MIDP 设备都支持Socket 网络。
在这部分中我们主要涉及到的两个接口是SocketConnection 和ServerSocketConnection。这
个两个接口的使用方法其实和J2SE 中的Socket 和ServerSocket 类的使用方法很相似。不同的是
ServerSocketConnection 中打开一个SocketConnection 作为监听者的方法是acceptAndOpen()。同
时你可以用getLocalAddress()和getLocalPort()两个方法获得本地的绑定IP 地址和所打开的端口
号,这样你就可以告诉另外一台MIDP 设备你所使用的IP 和端口,使得另一台MIDP 设备可以
连接到你的设备上。
在这里我们除了强调使用acceptAndOpen()从一个ServerSocketConnection 对象中打开一个
SocketConnection 作为监听者外,还要说明的是作为套接字我们是可以设置一些属性的,这些属
性的设置是通过SocketConnection.setSocketOption()方法来设置

 

package  socketText;

import  java.io.IOException;
import  java.io.InputStream;
import  java.io.OutputStream;

import  javax.microedition.io.Connector;
import  javax.microedition.io.ServerSocketConnection;
import  javax.microedition.io.SocketConnection;
import  javax.microedition.lcdui.Alert;
import  javax.microedition.lcdui.AlertType;
import  javax.microedition.lcdui.Command;
import  javax.microedition.lcdui.CommandListener;
import  javax.microedition.lcdui.Display;
import  javax.microedition.lcdui.Displayable;
import  javax.microedition.lcdui.Form;
import  javax.microedition.lcdui.StringItem;
import  javax.microedition.lcdui.TextField;
import  javax.microedition.midlet.MIDlet;
import  javax.microedition.midlet.MIDletStateChangeException;

/**
 * 
 * 
@author leilu 服务器端代码
 
*/

public   class  SocketServer  extends  MIDlet  implements  CommandListener, Runnable
{
    
private Display display;

    
private Form f;

    
private StringItem si;

    
private TextField tf;

    
private boolean stop;

    
// 创建Command对象
    private Command sendCommand = new Command("send", Command.ITEM, 1);

    
private Command exitCommand = new Command("Exit", Command.EXIT, 1);

    
// 输入流
    InputStream is;

    
// 输出流
    OutputStream os;

    
// Socket连接
    SocketConnection sc;

    
// Socket服务器连接
    ServerSocketConnection scn;

    
public SocketServer()
    
{
        display 
= Display.getDisplay(this);
        f 
= new Form("Socket Server");
        si 
= new StringItem("Status:"" ");
        
// 显示发送消息的控件
        tf = new TextField("Send:"""30, TextField.ANY);
        f.append(si);
        f.append(tf);
        f.addCommand(exitCommand);
       
// f.addCommand(sendCommand);
        f.setCommandListener(this);
        display.setCurrent(f);
        
// 启动线程
        Thread t = new Thread(this);
        t.start();

    }


    
protected void startApp() throws MIDletStateChangeException
    
{
        
// TODO Auto-generated method stub

    }


    
protected void pauseApp()
    
{
        
// TODO Auto-generated method stub

    }


    
protected void destroyApp(boolean arg0) throws MIDletStateChangeException
    
{
        
// TODO Auto-generated method stub

    }


    
public void commandAction(Command c, Displayable d)
    
{
        
if (sendCommand == c)
        
{
            
try
            
{
                os.write(tf.getString().getBytes());
                os.write(
" ".getBytes());
            }

            
catch (IOException e)
            
{
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        
else if (exitCommand == c)
        
{
            
try
            
{
                destroyApp(
false);
                
this.notifyDestroyed();
            }

            
catch (MIDletStateChangeException e)
            
{
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }


    }


    
public void run()
    
{
        si.setText(
"Waiting for connection");
        
// 创建一个服务器的ServerSocketConnection连接

        
try
        
{
            scn 
= (ServerSocketConnection) Connector.open("socket://:5000");
            
// 等待一个连接
            sc = (SocketConnection) scn.acceptAndOpen();
            
// 设置提示信息
            si.setText("Connection accepted");
            is 
= sc.openInputStream();
            os 
= sc.openOutputStream();
            
// 连接完成后允许发送
            f.addCommand(sendCommand);
            
// 读取客户端发来的消息

            
while (true)
            
{
                StringBuffer sb 
= new StringBuffer();
                
int c = 0;
                
// 读取数据
                while (((c = is.read()) != ' '&& (c != -1))
                
{
                    sb.append((
char) c);
                }

                
// 如果读取数据失败
                if (c == -1)
                
{
                    
break;
                }

                
// 显示客户端反发送过来的消息
                si.setText("Message receved-" + sb.toString());
            }

            si.setText(
"Connection is closed");
            
// 连接结束,则不实现发送按钮
            f.removeCommand(sendCommand);

        }

        
catch (IOException ioe)
        
{
            
if (ioe.getMessage().equals("ServerSocket Open"))
            
{
                
// 提示端口己经被占用
                Alert a = new Alert("Server""Port 5000 is already taken.",
                        
null, AlertType.ERROR);
                a.setTimeout(Alert.FOREVER);
                a.setCommandListener(
this);
                display.setCurrent(a);
            }

            
else
            
{
                
if (!stop)
                
{
                    ioe.printStackTrace();
                }

            }

        }

        
catch (Exception e)
        
{
            e.printStackTrace();
        }


    }


    
// 释放资源
    public void stop()
    
{
        
try
        
{
            stop 
= true;
            
if (is != null)
            
{
                is.close();
            }

            
if (os != null)
            
{
                os.close();
            }

            
if (sc != null)
            
{
                sc.close();
            }

            
if (scn != null)
            
{
                scn.close();
            }

        }

        
catch (IOException e)
        
{
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


}

 

 

package  socketText;

import  java.io.IOException;
import  java.io.InputStream;
import  java.io.OutputStream;

import  javax.microedition.io.ConnectionNotFoundException;
import  javax.microedition.io.Connector;
import  javax.microedition.io.SocketConnection;
import  javax.microedition.lcdui.Alert;
import  javax.microedition.lcdui.AlertType;
import  javax.microedition.lcdui.Command;
import  javax.microedition.lcdui.CommandListener;
import  javax.microedition.lcdui.Display;
import  javax.microedition.lcdui.Displayable;
import  javax.microedition.lcdui.Form;
import  javax.microedition.lcdui.StringItem;
import  javax.microedition.lcdui.TextField;
import  javax.microedition.midlet.MIDlet;
import  javax.microedition.midlet.MIDletStateChangeException;

public   class  SocketClient  extends  MIDlet  implements  Runnable, CommandListener
{
    
private Display display;

    
private Form f;

    
private StringItem si;

    
private TextField tf;

    
private boolean stop;

    
// 创建Command对象
    private Command sendCommand = new Command("send", Command.ITEM, 1);

    
private Command exitCommand = new Command("Exit", Command.EXIT, 1);

    
// 输入流
    InputStream is;

    
// 输出流
    OutputStream os;

    
// Socket连接
    SocketConnection sc;

    
public SocketClient()
    
{
        display 
= Display.getDisplay(this);
        f 
= new Form("Socket Server");
        si 
= new StringItem("Status:"" ");
        
// 显示发送消息的控件
        tf = new TextField("Send:"""30, TextField.ANY);
        f.append(si);
        f.append(tf);
        f.addCommand(exitCommand);
        f.addCommand(sendCommand);
        f.setCommandListener(
this);
        display.setCurrent(f);
        
// 启动线程
        Thread t = new Thread(this);
        t.start();
    }


    
protected void startApp() throws MIDletStateChangeException
    
{
        
// TODO Auto-generated method stub

    }


    
protected void pauseApp()
    
{
        
// TODO Auto-generated method stub

    }


    
protected void destroyApp(boolean arg0) throws MIDletStateChangeException
    
{
        
// TODO Auto-generated method stub

    }


    
public void run()
    
{
       
            
try
            
{
                
// 打开一个连接本地服务器的SocketConnection
                sc = (SocketConnection) Connector.open("socket://localhost:5000");

                si.setText(
"Connected to server");
                
// 设置提示信息
                si.setText("Connection accepted");
                is 
= sc.openInputStream();
                os 
= sc.openOutputStream();

                
// 读取服务器端发来的消息

                
while (true)
                
{
                    StringBuffer sb 
= new StringBuffer();
                    
int c = 0;
                    
// 读取数据
                    while (((c = is.read()) != ' '&& (c != -1))
                    
{
                        sb.append((
char) c);
                    }

                    
// 如果读取数据失败
                    if (c == -1)
                    
{
                        
break;
                    }

                    
// 显示消息
                    si.setText("Message receved-" + sb.toString());
                }

                
// 停止连接
                stop();
                si.setText(
"Connection is closed");
                
// 连接结束,则不实现发送按钮
                f.removeCommand(sendCommand);
            }

            
catch (ConnectionNotFoundException cnf)
            
{
             
                    
// 提示端口己经被占用
                    Alert a = new Alert("Client""please run server first.",
                            
null, AlertType.ERROR);
                    a.setTimeout(Alert.FOREVER);
                    a.setCommandListener(
this);
                    display.setCurrent(a);
            }

            
catch(IOException ioe)
            
{
               
                    
if (!stop)
                    
{
                        ioe.printStackTrace();
                    }

            
            }

            
catch (Exception e)
            
{
            
                e.printStackTrace();
            }


       

    }


    
public void commandAction(Command c, Displayable d)
    
{
        
if (sendCommand == c)
        
{
            
try
            
{
                os.write(tf.getString().getBytes());
                os.write(
" ".getBytes());
            }

            
catch (IOException e)
            
{
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        
else if (exitCommand == c)
        
{
            
try
            
{
                destroyApp(
false);
                
this.notifyDestroyed();
            }

            
catch (MIDletStateChangeException e)
            
{
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }


    }

    
public void stop()
    
{
        
try
        
{
            stop 
= true;
            
if (is != null)
            
{
                is.close();
            }

            
if (os != null)
            
{
                os.close();
            }

            
if (sc != null)
            
{
                sc.close();
            }

        }

        
catch (IOException e)
        
{
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值