Java实现简单的本机TCP协议双向通信

在完成了发送端与接收端的连接以后,可以进行双方的双向通信,这里的例子是SeverDemo在收到消息后回复一条消息给ClientDemo。

代码:

ClientDemo.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClientDemo {

	public static void main(String[] args) throws IOException{
		Socket s = new Socket("192.168.23.1", 10001);
		
		OutputStream os = s.getOutputStream();
		os.write("Can you read me?".getBytes());
		
		InputStream is = s.getInputStream();
		byte[] buf = new byte[1000];
		int length = is.read(buf);
		System.out.println("Information from " + s.getLocalAddress().getHostAddress() + " : " + new String(buf, 0, length));
		
		s.close();
	}
}

SeverDemo.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SeverDemo02 {

	public static void main(String[] args) throws IOException{
		ServerSocket ss = new ServerSocket(10001);
		
		Socket s = ss.accept();
		InputStream is = s.getInputStream();
		byte[] buf = new byte[1000];
		int length = is.read(buf);
		System.out.println("Information from " + s.getLocalAddress().getHostAddress() + " : " + new String(buf, 0, length));
		
		OutputStream  os = s.getOutputStream();
		os.write("Very clear.".getBytes());
		
		s.close();
	}

}

猜你喜欢

转载自blog.csdn.net/g28_gwf/article/details/80453986