JAVA網絡編程TCP案例

服務端

import java.net.*;
import java.io.*;

public class TCPServerSocket {
	public static void main(String[] args) throws Exception{
		String data = "";
		//while (true) {
			try{
				ServerSocket ss = new ServerSocket(8888);
				Socket s = ss.accept();
				InputStream in = s.getInputStream();
				int len = 0;
				byte[] buff = new byte[1024];
				while((len = in.read(buff)) > 0) {
					data += new String(buff,0,len);
				}
			} catch (Exception e){
				System.out.println("Exception");
			}
			System.out.println(data);
		//}
		
	}
}

客戶端

import java.net.*;
import java.io.*;
public class TCPSocket{
	public static void main(String[] args) throws Exception{
		int port = 8888;
		String ip = "127.0.0.1";
		//InetAddress address = InetAddress.getByAddress(stringToByte(ip));
		InetAddress address = InetAddress.getByName("localhost");
		Socket socket = new Socket(address, port);
		OutputStream out = socket.getOutputStream();
		String data = "hello";
		byte buff[] = data.getBytes();
		out.write(buff,0,buff.length);
		out.flush();
		socket.close();
	}

	public static byte[] stringToByte (String ip){
		String[] strArr = ip.split(".");
		byte[] IPArr = new byte[4];
		
		System.out.println(strArr.length);

		for(int i = 0; i < 4; i++){
			IPArr[i] = (byte)Integer.parseInt(strArr[i]); 
		}

		return IPArr;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章