基於TCP的客戶端和服務端資料傳輸
阿新 • • 發佈:2018-12-07
功能描述: 從客戶端向服務端傳送字串,服務端接收之後,把字串轉成大寫,並返回給客戶端,
客戶端程式碼
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class ClientDemo { public static void main(String[] args) throws IOException { //客戶端向服務點 傳送字串 Socket s = new Socket(InetAddress.getByName("SKY-20180725WBH"), 10010); OutputStream os = s.getOutputStream(); os.write("tcp, i am coming again!!!".getBytes()); // 接受服務端返回的資料 InputStream is = s.getInputStream(); byte[] bytes = new byte[1024]; int len; len = is.read(bytes); System.out.println(new String(bytes,0 ,len)); // 釋放Socket資源 s.close(); } }
服務端程式碼
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerDemo { public static void main(String[] args) throws IOException { // 接收客戶端的 資料 ServerSocket ss = new ServerSocket(10010); Socket s = ss.accept(); InputStream is = s.getInputStream(); byte[] bys = new byte[1024]; int len; len = is.read(bys); String str = new String(bys,0,len); System.out.println(str); // 將客戶端的資料轉成大寫 String upperStr = str.toUpperCase(); // 從服務端向客戶端 返回資料 OutputStream os = s.getOutputStream(); os.write(upperStr.getBytes()); s.close(); // 服務端的ServerSocket 可以不用釋放資源 // ss.close(); } }