客户端:
1 添加CFNetwork.framework到工程中
2 拖动AsyncSocket.h 和 AsyncSocket.m 到工程
3 然后实现方法
SocketDemoViewController.h
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
#define SRV_CONNECTED 0
#define SRV_CONNECT_SUC 1
#define SRV_CONNECT_FAIL 2
#define HOST_IP @"127.0.0.1"
#define HOST_PORT 8080
@interface SocketDemoViewController : UIViewController <UITextFieldDelegate>
{
UITextField *inputMsg;
UILabel *outputMsg;
AsyncSocket *client;
}
@property (nonatomic, retain) AsyncSocket *client;
@property (nonatomic, retain) UITextField *inputMsg;
@property (nonatomic, retain) UILabel *outputMsg;
- (int) connectServer: (NSString *) hostIP port:(int) hostPort;
- (void) showMessage:(NSString *) msg;
- (void) sendMsg;
- (void) reConnect;
//- (IBAction) textFieldDoneEditing:(id)sender;
- (IBAction) backgroundTouch:(id)sender;
@end
SocketDemoViewController.m
#import "SocketDemoViewController.h"
@implementation SocketDemoViewController
@synthesize inputMsg, outputMsg;
@synthesize client;
- (void)viewDidLoad {
//[super viewDidLoad];
//ui
inputMsg = [[UITextField alloc] initWithFrame: CGRectMake( 10.0f, 60.0f, 300.0f, 30.0f)];
inputMsg.placeholder = @"send message here";
inputMsg.delegate = self;
inputMsg.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview: inputMsg];
//output
outputMsg = [[UILabel alloc] initWithFrame: CGRectMake( 10.0f, 120.0f, 300.0f, 60.0f)];
outputMsg.textColor = [UIColor redColor];
outputMsg.backgroundColor = [UIColor blackColor];
[self.view addSubview: outputMsg];
//send button
UIButton *btnSend = [UIButton buttonWithType: UIButtonTypeRoundedRect];
btnSend.frame = CGRectMake(10.0f, 200.0f, 300.0f, 30.0f);
[btnSend setTitle: @"Send" forState: UIControlStateNormal];
[btnSend addTarget: self action: @selector(sendMsg) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview: btnSend];
UIButton *reConnect = [UIButton buttonWithType: UIButtonTypeRoundedRect];
reConnect.frame = CGRectMake(10.0f, 250.0f, 300.0f, 30.0f);
[reConnect setTitle: @"reConnect" forState: UIControlStateNormal];
[reConnect addTarget: self action: @selector(reConnect) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview: reConnect];
[self connectServer:HOST_IP port:HOST_PORT];
//监听读取
}
//链接server
- (int) connectServer: (NSString *) hostIP port:(int) hostPort{
if (client == nil)
{
client = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
//192.168.110.128
if (![client connectToHost:hostIP onPort:hostPort error:&err])
{
NSLog(@"%@ %@", [err code], [err localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
stringByAppendingString:hostIP]
message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
//client = nil;
return SRV_CONNECT_FAIL;
}
else
{
NSLog(@"Conectou!");
return SRV_CONNECT_SUC;
}
}
else
{
[client readDataWithTimeout:-1 tag:0];
return SRV_CONNECTED;
}
}
- (void) reConnect{
int stat = [self connectServer:HOST_IP port:HOST_PORT];
switch (stat) {
case SRV_CONNECT_SUC:
[self showMessage:@"connect success"];
break;
case SRV_CONNECTED:
[self showMessage:@"It's connected,don't agian"];
break;
default:
break;
}
}
- (void)sendMsg{
NSString *inputMsgStr = self.inputMsg.text;
NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];
NSLog(@"inputMsgStr is %@",content);
NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
[client writeData:data withTimeout:-1 tag:0];
//[data release];
//[content release];
//[inputMsgStr release];
//继续监听读取
//[client readDataWithTimeout:-1 tag:0];
}
#pragma mark -
#pragma mark close Keyboard
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[inputMsg resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[inputMsg resignFirstResponder];
return YES;
}
- (IBAction) backgroundTouch:(id)sender{
[inputMsg resignFirstResponder];
}
#pragma mark socket uitl
- (void) showMessage:(NSString *) msg{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
message:msg
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
#pragma mark socket delegate
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
[client readDataWithTimeout:-1 tag:0];
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"Error is %@", [err localizedDescription]);
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSString *msg = @"Sorry this connect is failure";
[self showMessage:msg];
[msg release];
client = nil;
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Hava received datas is :%@",aStr);
self.outputMsg.text = aStr;
[aStr release];
[client readDataWithTimeout:-1 tag:0];
}
#pragma mark dealloc
- (void)dealloc {
[client release];
[inputMsg release];
[outputMsg release];
[super dealloc];
}
@end
服务器端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class SocketServer {
public static ArrayList<Socket> socketList = new ArrayList<Socket>();
public static int number = 0;
public static void main(String[] args) {
try{
ServerSocket server = new ServerSocket(8080);
Socket socket;
int count = 0;
while (true) {
socket = server.accept();
count = count + 1;
System.out.println(socket.getInetAddress().getHostAddress());
ReadThread readThread = new ReadThread(socket);
readThread.start();
socketList.add(socket);
}
} catch(IOException e){
e.printStackTrace();
}
}
}
class ThreadSocketServer extends Thread {
Socket server;
public ThreadSocketServer(){
}
public ThreadSocketServer(Socket s) {
this.server = s;
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter pw = new PrintWriter(server.getOutputStream());
while (true) {
String s = br.readLine();
pw.println(s);
pw.flush();
System.out.println("Server:" + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ReadThread extends Thread {
private Socket socket;
public ReadThread(Socket socket){
this.socket = socket;
}
public void run() {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read=new String();
while(true)
{
read=br.readLine();
System.out.println(socket.getInetAddress().getHostAddress() +"client: "+read);
ArrayList<Socket> socketList = SocketServer.socketList;
for(int i = 0; i < socketList.size(); i ++){
Socket socket = socketList.get(i);
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println(read);
pw.flush();
}
if(read.equals("bye"))
{
break;
}
}
br.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文转自: http://blog.csdn.net/iorchid/article/details/6723653