本篇文章主要学习net包中socket类及serversocket的使用,亦即通常所说的socket编程(网络编程的方法很多,socket只是其中一种).初步学习,记下来,不对的地方请指教.程序代码如下:
服务器端代码:
package test.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class socketServer {
public static void main(String args[]){
try{
ServerSocket server = new ServerSocket(2000);
Socket client = server.accept(); //服务器侦听端口并接受到此套接字的连接
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); //接收客户端传递的数据流
PrintWriter out=new PrintWriter(client.getOutputStream()); //服务器的返回值
while(true){
String str = in.readLine();
System.out.println("Client: "+str);
out.println("... received!");
out.flush();
if (str.equals("end")){
break;
}
}
client.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
客户端程序代码:
package com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class clientSocket {
public static void main(String[] args){
try{
Socket server = new Socket("10.40.2.7",2000);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream())); //接收服务器信息
PrintWriter out = new PrintWriter(server.getOutputStream()); //向服务器发送信息
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); //接收键盘输入信息
while(true){
String outStr = wt.readLine();
out.println(outStr);
out.flush();
if (outStr.equals("end")){
break;
}
System.out.println(in.readLine());
}
server.close();
}catch(UnknownHostException e){
}catch(IOException e){
}
}
}
~~end.
其中服务器和客户端数据是通过socket对象进行传递的,socket.getInputStream()得到客户端(相对而言:程序本机就是服务器,别人就是客户机)传递过来的数据输入流;server.getOutputStream()是即将返回的数据输出流. 另,程序的测试需要同时启动客户端和服务器端程序.如果在一台机器上同样可以做这样的测试,在eclipse的console中display selected console的选项可以在服务器端程序控制台和客户端程序控制台间进行切换.