基于TCP协议的网络通信
1.TCP协议基础
IP协议负责将消息从一个主机传送到另外一个主机,消息在传递的过程中被分割成一个个小包。但是IP协议还不能解决数据分组在传输过程中可能出现的问题。因此,还需要TCP协议来提供可靠并且无差错的通信服务。
***TCP协议被称为端对端协议。***当一台计算机需要与另外一台远程计算机链接时,TCP协议会让他们建立一个链接——用于发送和接受数据的虚拟链路。
TCP协议使用的是重发机制:当一个通信实体发送一个信息给另外一个通信实体后,需要收到另外一个通信实体的确定信息,如果没有收到另外一个通信实体的确定信息,则会再次重发刚才发送的消息。
2.使用ServerSocket创建TCP服务器端
接收其他通信实体连接请求的类ServerSocket,ServerSocket对象用于监听来自客户端的Socket连接(如果没有连接,则会一直处于等待状态)。
ServerSocket包含一个监听来自客户端连接请求的方法,Socket accept():如果接受到一个客户端的Socket的连接请求,该方法将返回一个与连接客户端Socket对应的Socket
ServerSocket构造方法:
ServerSocket(int port):用指定的端口port来创建一个ServerSocket.
ServerSocket(int port,int backlog) :增加一个用来改变连接队列长度的参数backlog。
ServerSocket(int port,int backlog,InetAddress localAddr) :
在机器存在多个IP地址的情况下,允许通过loclAddr这个参数来指定将ServerSocket绑定到指定的IP地址。
使用Socket进行通信
客户端通常使用Socket构造器来连接到指定服务器,
Socket(InetAddress/String remoteAddress,int port) :创建连接到指定远程主机,远程端口的Socket,该构造器没有指定本地地址,本地端口,默认使用本地主机的默认IP地址,默认使用系统动态分配的端口。
Socket(InetAddress/String remoteAddress,int port,InetAddr localAddr , int localPort):创建连接到指定远程主机,远程端口的Socket,并指定本地地址,本地端口,适用于本地主机多个IP地址的情景。
上面两个构造器中指定远程主机时既可以使用InetAddress来指定,也可以使用String.通常使用String来指定。比如:192.168.2.23
//创建连接192.168.2.23,3000端口的Socket
Socket s = new Socket("192.168.2.23",3000);
//下面就可以使用Socket进行通信了
Socket提供两个方法来获取输入流和输出流。
InputStream getInputStream():返回该Socket对象对应的输入流,让程序通过该输入流从Socket中取数据。
OutputStream getOutputStream() :返回该Socket对象对应的输出流,让程序通过该输出流向Socket中输出数据。
服务端;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ServiceConfigurationError;
/**
* Created by zhaol on 2021/9/13.
*/
public class SimpleServer {
public static void main(String[] args) throws IOException{
System.out.println("Hello World!");
ServerSocket ss= new ServerSocket(30000);
while(true){
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write("您好,服务器收到了你的请求!".getBytes("UTF-8"));
//关闭输出流,关闭Socket
os.close();
s.close();
}
}
}
客户端:
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private Button button;
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "this is a Toast", Toast.LENGTH_SHORT).show();
}
});
textview = (TextView)this.findViewById(R.id.textView2);
new Thread(){
public void run(){
try {
//建立连接到远端服务器的Socket
Socket socket = new Socket("192.168.2.23", 30000);
//设置10秒之后认为超时
socket.setSoTimeout(10000);
//将Socket对应的输入流包装成BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//进行IO操作
String line = br.readLine();
textview.setText(line);
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
main_activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.zhaol.testactivity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试按钮"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="111dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试文本"
android:id="@+id/textView2"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/button"
android:layout_toStartOf="@+id/button" />
</RelativeLayout>
注意的是 ;要在Mainfest.xml中添加权限
<uses-permission android:name="android.permission.INTERNET" />
如果超时,则会抛出异常SocketTimeoutException
链接: https://blog.csdn.net/iispring/article/details/51474529.