java TCP socket编程2

来源:互联网 发布:部落城堡升级数据 编辑:程序博客网 时间:2024/06/15 16:07
import java.net.*;import java.io.*;public class TestServer {public static void main(String[] args) {try {ServerSocket s = new ServerSocket(28888);while(true){Socket s1=s.accept();OutputStream os=s1.getOutputStream();DataOutputStream dos = new DataOutputStream(os);dos.writeUTF("Hello,"+s1.getInetAddress()+"port#"+s1.getPort()+"bye-bye!");dos.close();s1.close();}} catch (IOException e) {// TODO: handle exceptione.printStackTrace();System.out.println("程序运行出错"+e);}}}
import java.net.*;import java.io.*;public class TestClient {public static void main(String[] args) {try {Socket s1=new Socket("127.0.0.1",28888);InputStream is=s1.getInputStream();DataInputStream dis=new DataInputStream(is);System.out.println(dis.readUTF());dis.close();s1.close();} catch (ConnectException connExc) {// TODO: handle exceptionconnExc.printStackTrace();System.err.println("服务器连接失败!");}catch (IOException e) {// TODO: handle exceptione.printStackTrace();}}}


0 0
原创粉丝点击