Socket网络编程

Client:

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s=new Socket("192.168.123.177",8888);
InputStream inp = s.getInputStream();
OutputStream outp = s.getOutputStream();
outp.write("Hell Server".getBytes());
byte[] b=new byte[1024];
int len=0;
len =inp.read(b);
String str1=new String(b,0 , len);
System.out.println(str1);
if (str1.equals("Hello client")) {
outp.write("Bye".getBytes());
}
len =inp.read(b);
String str2 = new String(b,0,len);
System.out.println(str2);
if(str2.equals("Bye")){
s.close();
}
}
}

Server:

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class server {
public static void main(String[] args) throws IOException {
ServerSocket s =new ServerSocket(8888);
Socket s1 = s.accept();
InputStream inp=s1.getInputStream();
OutputStream outp=s1.getOutputStream();
byte[] b=new byte[1024];
int len;
len =inp.read(b);
String str1=new String(b,0,len);
System.out.println(str1);
if(str1.equals("Hell Server")){
outp.write("Hello client".getBytes());
}
len =inp.read(b);
String str2=new String(b,0,len);
System.out.println(str2);
if(str2.equals("Bye")){
outp.write("Bye".getBytes());
s.close();
}
}
}

原文地址:https://www.cnblogs.com/joyous-day/p/8036784.html