android部分代码如下:
注意:在Manifest.xml中需要添加网络访问许可<uses-permission android:name="android.permission.INTERNET" />
package com.test.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SocketActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private TextView tv;
private Button btn, btn_exit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.message);
tv.setText("Ready");
btn = (Button)findViewById(R.id.send);
btn.setOnClickListener(this);
btn_exit = (Button)findViewById(R.id.exit);
btn_exit.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btn) {
tv.setText("Start");
int port = 7100;
try {
Socket socket = new Socket("10.10.15.79", port);
OutputStream out = socket.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF("Jordan");
InputStream in = socket.getInputStream();
DataInputStream din = new DataInputStream(in);
String str = din.readUTF();
tv.setText(str);
in.close();
out.close();
socket.close();
}catch (UnknownHostException e) {
// TODO: handle exception
tv.setText("UnknownHostError");
}catch (IOException e) {
// TODO: handle exception
tv.setText("IOError");
}
} else if (v == btn_exit) {
finish();
}
}
}
PC机端使用Java作为服务器,创建ServerSocket,之后等待客户端连接。具体代码如下:
import java.net.*;
import java.io.*;
public class SocketAppServer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket ss = null;
int port = 7100;
String hello="From Server:Hello World!";
//create ServerSocket
try {
ss = new ServerSocket(port);
}catch (IOException e) {
// TODO: handle exception
System.out.println(e);
System.exit(1);
}
//accept client connection
while(true) {
try {
System.out.println("Waiting for connection on port="+port);
Socket cs = ss.accept();
InputStream input = cs.getInputStream();
DataInputStream din = new DataInputStream(input);
String name = din.readUTF();
OutputStream output = cs.getOutputStream();
DataOutputStream dout = new DataOutputStream(output);
dout.writeUTF(hello+"Your name:"+name);
System.out.println("Connection OK port="+port);
System.out.println("=========================");
din.close();
output.close();
cs.close();
}catch (IOException e) {
// TODO: handle exception
System.out.println(e);
}
}
}
}