Establish TCP connection and send data in J2ME clients

xiaoxiao2021-03-06  78

The following is a client code: package testsocket; // Use the TCP protocol to create a one-time TCP connection // This example is to try to test the speed of establishing the TCP connection is how much; // From the experimental results, establish a connection speed The average time is less than 1 second, the average time between each connection is less than 1 second; // Test environment: peanut shell dynamic domain analysis, server side needs to run the service program; import javax.microedition.midlet. *; Import Javax.microedition.lcdui. *; import javax.microedition.io. *; import java.io. *; import javax.microedition.lcdui.command; import javax.microedition.lcdui.displayable;

public class Test extends MIDlet implements CommandListener {private static Test instance; Display display; Command exitCmd; Command connectCmd; Form result; String serverUrl = "socket: //zhang-yin.vicp.net: 4040"; String message; / ** Constructor * / public test () {Display = display.getdisplay (this); Result = new form ("get message"); exitcmd = new command (". EXIT.", Command.exit, 1); connectcmd = new Command ("Connected ...", command.screen, 1); result.addcommand; Result.AddCommand (ConnectCMD); Result.setCommandListener (THIS)

/ ** main method * / public void startapp () {Display.setCurrent (result);}

/ ** Handle Pausing The Midlet * / Public Void PauseApp () {}

/ ** Handle Destroying The Midlet * / Public Void DestroyApp (Boolean Unconditional) {}

/ ** quit the midlet * / public static void quitapp () {instance.destroyApp (true); instance.notifydestroyed (); instance = null;}

Public void CommandAction (Command C, Displayable D) {if (c == EXITCMD) {DestroyApp (TRUE); notifyDestroyed ();} else if (c == connectioncmd) {Try {

Connect (serverURL);} catch (exception ex) {}}}

Void Connect (String Url) throws oException {

Try {for (int i = 0; i <100; i ) {system.out.println ("now:" i); streamconnection con = (streamconnection) Connector.Open (URL); OutputStream Os = Con. OpenoutputStream Int Data; StringBuffer SB = new stringbuffer (); byte [] ff = new byte [12]; ff = "1234567890" .GetBytes (); os.write (ff); os.flush (); system.out .println ("send ok"); if (OS! = null) os.close (); if (con! = null) Con. close ();}} finally {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} Using system.drawing; using system.windows.forms; using system.net; using system.net.sockets; using system.threading; using system.io;

A summary description of Namespace TCPServer {///

/// Form1. /// public class server: system.windows.Forms.form {/// // The required designer variable. /// private system.componentmodel.container components = null;

Public Server () {// // Windows Form Designer Support for // InitializationComponent ();

// // Todo: Add any constructor code after INITIALIZEComponent call //}

///

/// Clean all the resources being used. /// Protected Override Void Dispose (Bool Disposing) {if (disponents! = Null) {components.dispose ();}} Base.Dispose (4);

private bool doIt = true; private Thread startServer; TcpListener serverListener; TcpClient tcpClient; System.Net.Sockets.NetworkStream netStream; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows. Forms.ListBox ListBox1; Private System.windows.Forms.Button Button3; int port = 4040; #Region Windows Form Designer Generated code ///

/// designer supports the required method - do not use code The editor modifies the content of the // this method.

/// private () {this.button1 = new system.windows.Forms.Button (); this.button2 = new system.windows.Forms.Button (); this.listbox1 = new system. Windows.Forms.Listbox (); this.button3 = new system.windows.Forms.Button (); this.suspendlayout (); /// Button1 // this.button1.location = new system.drawing.point (32 , 40); this.button1.name = "button1"; this.button1.size = new system.drawing.size (64, 24); this.button1.tabindex = 0; this.button1.text = "Start service" This.Button1.Click = new system.eventhandler (this.button1_click); // // button2 // this.button2.location = new system.drawing.point (112, 40); this.button2.name = " Button2 "; this.button2.size = new system.drawing.size (64, 24); this.button2.tabindex = 1; this.button2.text =" stop service "; this.button2.click = new system. EventHandler (this.button2_click; // // listbox1 // this.listbox1.itemheight = 12; this.listbox1.location = new system.drawing.poin T (32, 72); this.listbox1.name = "ListBox1"; this.listbox1.size = new system.drawing.size (344, 184); this.listbox1.tabindex = 2; // // Button3 // This.Button3.Location = new system.drawing.point (304, 40); this.button3.name = "button3"; this.button3.size = new system.drawing.size (64, 24); this.button3. Tabindex = 3; this.button3.text = "Clear list"; this.button3.click = new system.eventhandler (this.button3_click); /// server // this.autoscalebasesize = new system.drawing.size 6, 14); this.clientsize =

New system.drawing.size (400, 349); this.controls.add (this.button3); this.controls.add (this.listbox1); this.controls.add (this.button2); this.controls.add (this.button1); this.name = "server"; this.text = "TCP server program"; this.Load = new system.eventhandler (this.server_load); this.ResumeLayout (false);} #ENDREGION

///

/// The primary entry point of the application. /// [stathread] static void main () {Application.run (new server ());}

Public void startlisten () // User request {serverListener.start () // launch listening while (DOIT) // enters unlimited loop Waiting for the user to connect {TRPCPCPCPClient (); // create a client connection object netStream = tcpClient.GetStream (); // get the network stream // BinaryReader br = new BinaryReader (netStream); StreamReader sr = new StreamReader (netStream); string buffer = ""; string received = " "; Received = sr.readline (); // read traffic one line while (receive = Received; buffer =" / r / n "; received = sr.readline (); if (Received) == null) {received = "";}} listbox1.items.add (buffer); // Display} catch (exception re) {messagebox.show (Re.Message);}} // while netstream.close () TcpClient.close ();

Public void run () {// Opening a thread StartServer = new thread (new threadstart (startlisten)); // Start thread startserver.start ();

Private void button1_click (object sender, system.eventargs e) {// Start service DOIT = true; this.button2.enabled = true; button1.enabled = false; run ();

private void button2_Click (object sender, System.EventArgs e) {// stop the service doIt = false; button1.Enabled = true; button2.Enabled = false; startServer.Abort (); serverListener.Stop ();} private void Server_Load ( Object sender, system.eventargs e) {try {serverListener = new tcplistener (ipaddress.any, port); // Create a TCPListener object instance} catch (exception ex) {messagebox.show ("Can't Start Server" EX. Message); Return;}}

Private void button3_click (object sender, system.eventargs e) {this.listbox1.items.clear ();

} // End class server}

转载请注明原文地址:https://www.9cbs.com/read-93650.html

New Post(0)