关于socket的简单的客户服务端编程

public class Server {
private ServerSocket ss;
private Socket socket;// 用来接收客户端的socket
private BufferedReader in;// 读取客户端发来的信息


public Server() {
try {
ss = new ServerSocket(10000);
while (true) {
System.out.println("等待接收:");
socket = ss.accept();// 连接客户端
System.out.println("从" + socket.getRemoteSocketAddress()
+ "连接成功");


in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));// 得到客户端的输入流
String socketText = in.readLine();// 获取客户端的内容
System.out.println(" 客户端说:" + socketText);
in.close();
socket.close();
}


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


/**
* @param args
*/
public static void main(String[] args) {
new Server();
}


}


***********************************************************************

package arthur.java.socket.demo;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


public class Client {
private Socket socket;
private PrintWriter out;
private String clientName;


public Client(String clientName) {
this.clientName = clientName;
this.connect();


}


public Client() {
this(null);
this.connect();
}


public void connect() {
try {
socket = new Socket("127.0.0.1", 10000);
System.out.println("请输入信息:");
out = new PrintWriter(socket.getOutputStream(), true);


BufferedReader line = new BufferedReader(new InputStreamReader(
System.in));// 从控制台输入信息


out.println(line.readLine());// 输入信息到服务器
out.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/**
* @param args
*/
public static void main(String[] args) {
new Client();


}


}


*****************************************************************************************************

运行结果

先运行服务器显示

等待接收:

然后运行客户端:请输入信息:我爱java

服务器显示:从/127.0.0.1:60139连接成功
 客户端说:我爱java







你可能感兴趣的:(java,String,server,socket,服务器,Class)