socket编程
通过socket在本机上通信:
TCPClient.java
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; public class TCPClient { public static void main(String[] args) throws UnknownHostException, IOException { String sentence; //存储用户输入的字符串 String modifiedsentence; //存储经过服务器修改的字符串 BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));//创建一个从标准输入流输入的对象 Socket clientSocket=new Socket("127.0.0.1",9999);//建立一个socket对象.127..0.0.1表示本机
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());//创建一个经由tcp的输出对象 BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));//创建一个经由tcp的输入对象 sentence=inFromUser.readLine();//读取用户的输入 outToServer.writeBytes(sentence+'\n');//将用户数据传入到服务器 modifiedsentence=inFromServer.readLine();//将修改后的数据接收回来 System.out.println(modifiedsentence);//在标准输出上输出字符串 clientSocket.close(); } }
TCPServer.java
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { String clientSentence; String capitalizedSentence; @SuppressWarnings("resource") ServerSocket welcomeSocket=new ServerSocket(9999); while(true){ Socket connectionSocket=welcomeSocket.accept(); BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream()); clientSentence=inFromClient.readLine(); capitalizedSentence=clientSentence.toUpperCase()+'\n'; outToClient.writeBytes(capitalizedSentence); } } }