CS175
Chris Pollett
Oct 29, 2014
#import < UIKit/UIKit.h> #include < sys/types.h> #include < sys/socket.h> #include < netinet/in.h> #include < netdb.h> @interface ViewController : UIViewController < UITableViewDelegate, UITableViewDataSource> @property (nonatomic, copy) NSArray *listData; @end
// // ViewController.m // NetworkExample // // Created by Chris Pollett on 10/29/14. // Copyright (c) 2014 Chris Pollett. All rights reserved. // #import "ViewController.h" CFSocketNativeHandle sock; UInt8 buffer[1024]; void ConnectCallBack( CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { sock = CFSocketGetNative(socket); char *msg = info; NSLog(@"%s\n", msg); send(sock, msg, strlen(msg) +1, 0); NSLog(@"Sent Message\n"); recv(sock, buffer, sizeof(buffer), 0);// if wanted to write could use NSLog(@"Got: %s \n", buffer); CFRunLoopStop(CFRunLoopGetCurrent()); return; } @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; char msg[] = "HELLO\n"; /* Build our socket context; this ties the joke to the socket */ CFSocketContext context = { 0, msg, NULL, NULL, NULL }; CFSocketRef client = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketConnectCallBack, (CFSocketCallBack)ConnectCallBack, &context); struct sockaddr_in theName; struct hostent *hp; CFDataRef addressData; theName.sin_port = htons(8889); theName.sin_family = AF_INET; hp = gethostbyname("localhost"); if( hp == NULL ) { return; } memcpy( &theName.sin_addr.s_addr, hp-> h_addr_list[0], hp-> h_length ); addressData = CFDataCreate( NULL, (UInt8 *)&theName, (CFIndex)sizeof( struct sockaddr_in ) ); CFSocketConnectToAddress(client, addressData, 1); // 1 second timeout CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, client, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes); CFRelease(sourceRef); CFRunLoopRun(); NSLog(@"I got: %s\n\n", buffer); NSString *data = [[NSString alloc] initWithCString: (char*)buffer encoding: NSASCIIStringEncoding]; NSArray *list_array = [data componentsSeparatedByString:@":"]; self.listData = list_array; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - #pragma mark Table View Data Source Methods /* notice we have two methods to implement our protocols */ /* This method gives for each section in the table the number of rows it has (we only have one section so in this case it returns the total number of rows) */ -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section { return [self.listData count]; } /* This method is a callback used to fill in table cells. Notice to save memory we only instiate cells which will be scene, but then we cache them when they become invisible */ -(UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { /* Name we will use for our type of table cell (if have more than one type) we might have more than one name. For example, we might have image and non image cells */ static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; if(cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: SimpleTableIdentifier]; } NSUInteger row = [indexPath row]; cell.textLabel.text = self.listData[row]; /* If we want to style our cells we can do things like: cell.textLabel.font = [UIFont boldSystemFontOfSize:50]; */ return cell; } @end
request = new XMLHttpRequest()
request.setRequestHeader("name", "value")
request.open(theHTTPmethod, theURL, theAsync flag) or request.open(theHTTPmethod, theURL, theAsync flag, username, password)
request.open("GET", "progress.php", true)
var self = this; /* remember scope of enclosing object */ request.onreadystatechange = function() { switch(request.readyState) { case 0:// handle uninitialized case case 1: // handle open but no send case case 2: // handle send but no response case case 3: // handle response is being downloaded case case 4: // handle response has completed being downloaded case } }
document.getElementById("myDivTag").innerHTML = request.responseText; //or we could do... myDiv = document.getElementById("myDivTag") if(myDiv.firstChild) { myDiv.removeChild(myDiv.firstChild); } myDiv.appendChild(document.createTextNode(request.responseText));
request.send(null);Note: send's argument can be used if using POST method to send the posted data
function downloadDelayed() { $.ajax({ url : "myscript.php", success : function (data) { $("#contentArea").html(data); } }); } setTimeout("downloadDelayed()", 1000);
GET /mychat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat Sec-WebSocket-Version: 13 Origin: http://example.com
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat
Below are the basic WebSocket Javascript functions (websocket URI's are prefixed with ws: or wss: (secure)):
var webSocket = new WebSocket("ws://some.websocketplace.org"); // Associate listeners webSocket.onopen = function(evt) { alert("The connection was opened"); }; webSocket.onmessage = function(evt) { alert("Received message: " + evt.data); }; webSocket.onclose = function(evt) { alert("The connection was closed"); }; webSocket.onerror = function(evt) { alert("Ouch an error!"); }; webSocket.send("This is some WebSocket data!"); // Close WebSocket webSocket.close();
package org.pollett; import android.app.*; import android.widget.*; import android.os.Bundle; public class ListViewTest extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FOOD)); getListView().setTextFilterEnabled(true); } static final String[] FOOD= new String[] { "Pizza", "Apple", "Calzone", "Ma Po Do Fu", "Pho Bo", "Curry", "Coffee", "Catfish" }; }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="8dp" android:paddingRight="8dp"> <ListView android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="200sp" android:background="#00FF00" android:layout_weight="1" android:drawSelectorOnTop="false"/> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#EEEEEE" > <Button android:id="@+id/mybutton" android:layout_width="100sp" android:layout_height="wrap_content" android:text="Button" android:layout_x="19px" android:layout_y="347px" /> </LinearLayout> </LinearLayout>
package org.pollett; import android.app.*; import android.content.DialogInterface; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; import android.os.Bundle; public class ListViewTest extends ListActivity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { View button; super.onCreate(savedInstanceState); setContentView(R.layout.main); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FOOD)); getListView().setTextFilterEnabled(true); button = this.findViewById(R.id.mybutton); button.setOnClickListener(this ); } protected void onListItemClick(ListView l, View v, int position, long id) { AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("List Item Clicked"); alertDialog.setMessage("You clicked list item " + position); alertDialog.setButton("Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); alertDialog.show(); } public void onClick(View v) { AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Button Clicked"); alertDialog.setMessage("You clicked the button"); alertDialog.setButton("Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); alertDialog.show(); } static final String[] FOOD= new String[] { "Pizza", "Apple", "Calzone", "Ma Po Do Fu", "Pho Bo", "Curry", "Coffee", "Catfish" }; }
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1"> <TableRow> <TextView android:layout_column="1" android:text="Open..." android:padding="3dip" /> <TextView android:text="Ctrl-O" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:layout_column="1" android:text="Save..." android:padding="3dip" /> <TextView android:text="Ctrl-S" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> <TableRow> <TextView android:text="X" android:padding="3dip" /> <TextView android:text="Import..." android:padding="3dip" /> </TableRow> </TableLayout>