至 Java 官方網站下載 JDK 環境來安裝
選擇單純的
Java SE Development Kit (JDK)
JDK 6 Update 16
This special release provides a few key fixes.
來安裝即可,記得要先把舊版的 Java 都先移除乾淨。
接著再按照此網站來設定環境變數,便可在命令提示字元作編譯跟執行的動作。
以下是 TCP Socket 的 Java code... 其中 127.0.0.1 為本機位址,1234是隨便開的 port number
程式會將 Clinet 送過去的字串轉成大寫送回。
// Server端
import java.lang.*;
import java.io.*;
import java.net.*;
class Socket_Server
{
public static void main(String args[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(1234);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader
(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream
(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("1234: " + clientSentence );
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
// Client端
import java.lang.*;
import java.io.*;
import java.net.*;
class Socket_Client
{
public static void main(String args[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader
(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 1234);
DataOutputStream outToServer = new DataOutputStream
(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader
(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
沒有留言:
張貼留言