java的socket编程源码

package c;

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

public class GreetingClient {

	public static void main(String[] args) {
		try (Socket s = new Socket("127.0.0.1", 8888)) {
			System.out.println("连到了服务段 " + s.getRemoteSocketAddress());
			OutputStream os = s.getOutputStream();
			DataOutputStream out = new DataOutputStream(os);
			out.writeUTF("你好我是客户端 " + s.getLocalSocketAddress());

			InputStream is = s.getInputStream();
			DataInputStream in = new DataInputStream(is);
			System.out.println("服务段说:" + in.readUTF());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
package s;

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

public class GreetingServer implements Runnable {

	public void run() {
		while (true) {
			try (ServerSocket ss = new ServerSocket(8888);) {
				System.out.println("等待客户端连接");
				try (Socket s = ss.accept()) {
					InputStream is = s.getInputStream();
					DataInputStream in = new DataInputStream(is);
					System.out.println(in.readUTF());

					OutputStream os = s.getOutputStream();
					DataOutputStream out = new DataOutputStream(os);
					out.writeUTF("我市服务段 " + s.getLocalSocketAddress());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		GreetingServer gs = new GreetingServer();
		Thread t = new Thread(gs);
		t.run();
	}
}
发布了253 篇原创文章 · 获赞 25 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/eds124/article/details/87899421
今日推荐