TCP Socket通信

package jave;
import java.io.*;
import java.net.*;
/*先启动Server*/
public class TCPServer {

	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(6666);//监听在6666端口上
		while(true) { //可以连接多个
			Socket s = ss.accept();//接收Client端的连接
			//接受Client端发来的东西
			DataInputStream dis = new DataInputStream(s.getInputStream());
			System.out.println(dis.readUTF());
			dis.close();
			s.close();
		}
	}
}

注意:Server只需启动一次,切勿重复启动,否则会出错

package jave;
import java.io.*;
import java.net.*;

import org.omg.CORBA.portable.OutputStream;
public class TCPClient {

	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		Socket s = new Socket("127.0.0.1", 6666);//申请链接
		//通过管道往Server里写东西
		java.io.OutputStream os =  s.getOutputStream();
		DataOutputStream dos = new DataOutputStream(os);
//		Thread.sleep(3000);//延迟3s让Server读取
		dos.writeUTF("Hello Server!");
		dos.flush();
		dos.close();
		s.close();
	}

}

猜你喜欢

转载自blog.csdn.net/wangjian530/article/details/82899861