Java Socket Demo

 

package srtp;

import java.io.*;
import java.net.*;

public class Client {
	Socket socket;
	BufferedReader in;
	PrintWriter out;

	
	public Client()  {
		try {
			socket = new Socket("localhost", 6363);
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());
			BufferedReader line = new BufferedReader(new InputStreamReader(
					System.in));

			// 从控制台读入数据,输出到Socket			
			String input=line.readLine();
			out.println(input);
			out.flush();	// 一定要flush
			
			// 从Socket 中读出服务器端的返回
			String s=in.readLine();
			System.out.println(s);
			
			in.close();
			out.close();
			line.close();
			socket.close();
		} catch (IOException e) {
		}
	}

	public static void main(String[] args) {
		new Client();
	}
}

 

客户端:

 

package srtp;

import java.net.*;
import java.io.*;

public class Server {
	private ServerSocket ss;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;


	public Server() {
		try {
			ss = new ServerSocket(6363);	//端口

			while (true) {
				socket = ss.accept();
				in = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));
				out = new PrintWriter(socket.getOutputStream(), true);

				// 从Socket中 输入 数据
				String s = in.readLine();
				
				// 处理
				s="Server: "+s;
				
				// 把结果输出到 Socket中
				out.println(s);
				out.flush();
				
				out.close();
				in.close();
				socket.close();
			}

		} catch (IOException e) {
		}
	}

	public static void main(String[] args) {
		new Server();
	}
}

启动 Server

启动 Client

 结果:

Hello

Server:Hello

你可能感兴趣的:(java,.net,socket)