首页 > 代码库 > Java网络编程(ServerSocket和Socket)

Java网络编程(ServerSocket和Socket)

服务器端


package org.tcp;


import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;


public class HelloServer {
public static void main(String[] args) throws Exception{
ServerSocket server = null;
Socket client = null;
PrintStream out = null;
server = new ServerSocket(8888);
System.out.println("服务器与性,等待客户端链接");
client = server.accept();
String str = "hello world!!!";
out = new PrintStream(client.getOutputStream());
out.println(str);
out.close();
client.close();
server.close();
}
}


程序运行结果:服务器运行,等待客户端链接


客户端


package org.tcp;


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


public class HelloClient {
public static void main(String[] args) throws Exception{
Socket client = null;
client = new Socket("localhost",8888);
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = buf.readLine();
System.out.println("服务器端输出内容:"+str);
client.close();
buf.close();
}
}


程序运行结果:服务器端输出内容:hello world!!!