Socket通信:
首先要创建一个server端(服务器端)和一个Client端(客户端)
1、Server端:
public static ArrayListsocketList = new ArrayList();//创建一个用于储存客户链接的list
public static String content="";
ServerSocket ss=new ServerSocket(1);//这里是端口号,可以自行设置
System.out.println("server on");
while(true){
InetAddress string;
Socket s = ss.accept();//接受客户端的连接请求
string= s.getInetAddress();//获取客户端的ip地址
System.out.println(string+" connect success!");
//若客户端与服务器链接成功,将link success信息写入到客户端
os1=s.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os1));
bw.write("link success\n");
bw.flush();
socketList.add(s);
new Thread(new ServerThread(s)).start();//创建线程来处理客户端的信息
}
ServerThread的代码:
public class ServerThread implements Runnable{//导入接口Runnable
private Socket mSocket = null;
private BufferedReader mBufferedReader = null;
public ServerThread(Socket socket) throws IOException{
mSocket = socket;
//把由客户端传入的信息包装成BufferedReader
mBufferedReader = new BufferedReader(
new InputStreamReader(mSocket.getInputStream()));
}
@Override
public void run(){
try{
String content = null;
while ((content = mBufferedReader.readLine()) != null) {
//输出客户端的信息
System.out.println(content);
for (Iteratorit = server.socketList.iterator();it.hasNext();) {//对list中的每一个客服端进行遍历
Socket s = it.next();
try {
OutputStream os = s.getOutputStream();
os.write((content + "\n").getBytes("utf-8"));//将刚才封装的BufferedReader流写入到客户端中并用utf-8的编码方式
} catch (SocketException e) {
e.printStackTrace();
it.remove();//若无法写入就从中移除
}
}
}
}catch (IOException e) {
e.printStackTrace();
server.socketList.remove(mSocket);//若客户端断开连接就从list中移除
}
}
}
2、Client端:
public classMainActivityextendsAppCompatActivity {
//定义控件
privateEditTextetMain;
privateButtonbtnMain;
privateTextViewtvMain;
privateClientmClientThread;
privateHandlermHandler;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etMain= (EditText) findViewById(R.id.et_main);
btnMain= (Button) findViewById(R.id.btn_main);
tvMain= (TextView) findViewById(R.id.tv_main);
btnMain.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View v) {
try{
Message msg =newMessage();
msg.what=1;
msg.obj=etMain.getText().toString();//将EditText的内容截取下来
mClientThread.revHandler.sendMessage(msg);
etMain.setText("");//清空EditText的内容方便下次用户写入内容
}catch(Exception e) {
e.printStackTrace();
}
}
});
mHandler=new Handler() {//将子线程的msg信息zai主线程里TextView显示用handler
@Override
public void handleMessage(Message msg) {
if(msg.what==0) {
tvMain.append("\n"+ msg.obj.toString());
}
}
};
mClientThread=new Client(mHandler);
newThread(mClientThread).start();//创建线程处理数据
}
}
Client函数代码:
public class Client implements Runnable{
privateSocket mSocket;
private BufferedReader mBufferedReader=null;
private OutputStream mOutputStream=null;
private Handler mHandler;
public Handler revHandler;
public Client(Handler handler){
mHandler= handler;
}
public void run(){//连接Server端
try{
mSocket=new Socket("192.168.1.106",1);
mBufferedReader=newBufferedReader(newInputStreamReader(mSocket.getInputStream()));//将服务器的写入信息包装成BufferedReader流;
mOutputStream=mSocket.getOutputStream();//客户端对服务器的写入
newThread(){
@Override
public void run() {
super.run();//调用父类的run方法
try{
String content =null;
while((content =mBufferedReader.readLine()) !=null) {//若信息不为空
Message msg =newMessage();
msg.what=0;
msg.obj= content;
mHandler.sendMessage(msg);//将msg传到主线程中
}
}catch(IOException e){
e.printStackTrace();
}
}
}.start();
Looper.prepare();//创建消息队列
revHandler=newHandler() {
@Override
public voidhandleMessage(Message msg) {
if(msg.what==1) {//当msg.what==1时将EditText里的信息发送到服务器
try{
mOutputStream.write((msg.obj.toString() +"\r\n").getBytes("utf-8"));
}catch(IOException e) {
e.printStackTrace();
}
}
}
};
Looper.loop();//取出信息
}catch(IOException e) {
e.printStackTrace();
}
}
}
activity_main.xml控件代码:
<Button
android:id="@+id/btn_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<EditText
android:id="@+id/et_main"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_alignTop="@+id/btn_main"
android:layout_toLeftOf="@+id/btn_main"
android:layout_toStartOf="@+id/btn_main"/>
<TextView
android:id="@+id/tv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/btn_main"/>
网友评论