您的位置:首页 > 其它

Socket通信

2015-06-10 17:05 204 查看
1、客服端发送并读取Socket:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import cm.example.constant.Constant;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class ReadSockeOracleThread extends SocketInit implements Runnable{

private Socket s;
BufferedReader br = null;
OutputStream out = null;
String content;

@Override
public void run() {

try {
//端口号与服务器端一致
s = new Socket("192.168.1.103",4001) ;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = s.getOutputStream();
try {
//发送socket数据
out.write(("you sent socket content"+"\n").getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(){
public void run() {
while(true){
try {
//接受socket数据
while((content = br.readLine())!=null){

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

}
}


2、服务器端:与Android类似。一般为了能和多个服务器通信,所以一般服务器利用线程通信。

-主函数:


public class SocketService {

public static int i=0;
public static void main(String[] args) throws Exception {
//端口号与Android端一致
ServerSocket ss = new ServerSocket(40001);
while(true){
Socket s = ss.accept();
i++;
new Thread(new SocketThread(s)).start();
System.out.println("Socket"+"*****************"+i);
}
}
}


-子线程:


public class SocketThread implements Runnable{

String content = null;//用户发过来的数据
OutputStream out = null;
BufferedReader br= null;
Socket s = null;

public SocketThread(Socket s) throws IOException {
this.s = s ;
br = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8"));
}
@Override
public void run() {

while((content = readFromClient()) != null){
System.out.println(content+"\n");
sendMsg(content);
}
//
}

//发送数据
public void sendMsg(String content){

if(content.equals("")){
try {
out = s.getOutputStream();
out.write((content+"\n").getBytes("UTF-8"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("发送成功");

}
}
//读取用户发送的状态数据
private String readFromClient(){
try {
return br.readLine();
} catch (Exception e) {
try {
s.close();
br.close();
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
return null;
}
}


`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: