1.新建一个java工程做服务器
public class MyServer {
String str ;
public MyServer(){
try {
//服务器端的声明用serversocket,括号里面写端口号,端口号是自己指定的
ServerSocket ss = new ServerSocket(4700);
//accept方法在这里会一直等待客户端连接进来
Socket accept = ss.accept();
//新建一个读入流,字符集是utf-8
BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream(),"utf-8"));
//用这个方法读取客户端写入的数据
str = br.readLine();
System.out.println("从客户端来的数据:"+ str);
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String [] args){
//不要忘了这一步
new MyServer();
}
}
2.新建一个android工程作为客户端
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//这里用到子线程有很多理由,可以自己百度了解一下
new Thread(){
public void run() {
try {
//cmd ipconfig获取当前本机ip地址
Socket client = new Socket("192.168.56.1", 4700);
//一定要要以换行符结尾,不然readline会一直读取不会停止,所以reaeline没有值返回
String str = "你好服务器\n";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
bw.write(str);
bw.flush();
bw.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
时间: 2024-11-03 22:34:25