TCP通信
客户端代码实现
package Study;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(" 192.168.0.102",8888);
OutputStream os=socket.getOutputStream();
os.write("你好服务器".getBytes());
socket.close();
}
}
服务器端代码实现
package Study;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(8888);
Socket socket=server.accept();
InputStream is=socket.getInputStream();
byte[] bytes=new byte[1024];
int len=is.read(bytes);
System.out.println(new String(bytes,0,len));
OutputStream os=socket.getOutputStream();
os.write("收到谢谢".getBytes());
socket.close();
server.close();
}
}