连接来自java写的服务器,连接成功后在textview中输出“连接服务器成功!”
服务器端:
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(30000);
while(true) {
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("连接服务器成功!");
ps.close();
s.close();
}
}
}客户端:
package com.example.yanzhuang.caculation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class Main6Activity extends AppCompatActivity implements View.OnClickListener {
TextView tv1;
TextView tv2;
TextView tv3;
EditText et1;
EditText et2;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn:
new Thread(new Runnable() {
@Override
public void run() {
String s1 = null;
String s2 = null;
s1 = et1.getText().toString();
s2 = et2.getText().toString();
try {
Socket socket = new Socket(s1, Integer.parseInt(s2));
BufferedReader br = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String line = br.readLine();
Log.d("Main6Activity", "line:" + line);
tv3.setText(line);
br.close();
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
break;
default :
break;
}
}
}布局文件:
app界面:
最终目标是要写个tcp调试助手的。