Server:

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


public class server implements Runnable
{
	private int port;
	private ServerSocket sc;
	
	public server(int port)throws IOException
	{
		this.port = port;
		//建立ServerSocket
		this.sc = new ServerSocket(port);
	}
	public void run()
	{
		Socket con = null;
		while(true)
		{
			System.out.println("等待連線.....");
			try
			{
				con = this.sc.accept();
				//取得Client的IP
				System.out.println(con.getInetAddress());
				
				//取得client資料
				System.out.println("取得資料:");
				DataInputStream in = new DataInputStream(con.getInputStream());
				System.out.println("Client:"+in.readUTF());
				
				//對client傳輸資料
				DataOutputStream out = new DataOutputStream(con.getOutputStream());
				out.writeUTF("我是Server");
				out.flush();
				//關閉socket
				con.close();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	public static void main(String [] argv)throws IOException
	{
		//new出一個thread
		Thread socket_thread = new Thread(new server(1234));
		socket_thread.start();
	}
}

Client:

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

public class client
{
	public static void main(String [] argv)throws IOException
	{
		StartClient(1234);
	}
	public static void StartClient(int port)
	{
		try
		{
			//設定連線的主機位置
			InetAddress add = InetAddress.getByName("ecc.johnsonlu.org");
			SocketAddress sc_add= new InetSocketAddress(add,port);
			Socket sc = new Socket();
			int timeout = 2000 ; //timeout 2秒
			System.out.println("連線中....");
			//與主機連線
			sc.connect(sc_add,timeout);
			System.out.println(sc.getLocalAddress() + "連線到" + sc.getInetAddress());
			
			//傳送資料到Server端
			DataOutputStream out = new DataOutputStream(sc.getOutputStream());
			out.writeUTF("我是Client");
			out.flush();
			
			//接收Server端資料
			DataInputStream in = new DataInputStream(sc.getInputStream());
			System.out.println("Server:" + in.readUTF());
			
			
		}
		catch(SocketTimeoutException e)
		{
			System.out.println("Timeout");
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
}

DataInputStream 和 DataOutputStream的用法
read(write)
read(write)Boolean
read(write)Byte
read(write)Bytes
read(write)Char
read(write)Chars
read(write)Double
read(write)Float
read(write)Int
read(write)Long
read(write)Short
read(write)UTF

Categories: Java