socket使用相关
时间:2021-07-01 10:21:17
帮助过:9人阅读
在一个练习小项目中学习到的
- package com.sdut.edu.tools;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.InetSocketAddress;
- import java.net.Socket;
- import java.net.SocketAddress;
- import java.net.SocketException;
- import java.util.Scanner;
- import android.app.ActivityManager;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.util.Log;
- public class ConnectServer {
- public String connectServer(String str) throws SocketException,IOException
- {//获得从服务器的响应字符串
- // TODO Auto-generated method stub
- String result = null;
- StringBuffer tempStr=new StringBuffer();//最终返回的结果
- // try{
- int c=0;
- //根据服务器的IP和端口号创建一个socket对象,建立与服务器的连接
- Socket socket=new Socket();
- //Socket的构造方法,
- socket.connect(new InetSocketAddress("192.168.0.189",4444),4000);
- //接收从服务器获得的数据额对象
-
- // if(socket.getRemoteSocketAddress()==null)
- // {
- //
- // }
- //socket.connect(remoteAddr);
- //BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"),10000);
- InputStream is=socket.getInputStream(); //接收数据的转码问题
-
- Scanner in=new Scanner(is);
- //根据已经建立的socket创建PrintWriter对象,并通过这个对象将信息发送给服务器。
- PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")),true);
- //消息发送
- out.println(str);
-
- Log.d("ListAdapter_getvediourl_isConnected",socket.isConnected()+"");
- //判断连接超时
- if(socket.isConnected())//判断客户端与服务器端的连接,接收响应的字符串
- {
- while(in.hasNextLine())
- {
- result=in.nextLine();
- tempStr.append(result);
- System.out.println(tempStr);
- }
- }
- else
- {
- System.out.println("连接服务超时");
- }
- out.close();
- in.close();
- socket.close();//完成后。关闭socket
-
- // }catch(SocketException e)
- // {
- // return "-1";
- // //System.out.println("连接失败");
- // //e.printStackTrace();
- // }catch(IOException e){
- // return "-2";
- // }
- return tempStr.toString();
- }
- }
|