//第一个项目
package com.itheima;
import java.net.*;
import java.io.*;
class TCPSever{
private static final int PORT = 7788;
public static void listen()throws Exception{
ServerSocket serverSocket = new ServerSocket(PORT);
while(true)
{
final Socket client = serverSocket.accept();//服务器接收端
new Thread(){
public void run(){
OutputStream os;
InputStream it;
try{
os = client.getOutputStream();
System.out.println("开始与客户端交互数据");
os.write(("连接成功").getBytes());
//字符串反转
it = client.getInputStream();
byte[] buf = new byte[1024];
int len = it.read(buf);
System.out.println("进行字符反转");
String str = new String(buf, 0, len);
StringBuffer st = new StringBuffer();
st.append(str);
os.write(("反转后的字符串为:"+ st.reverse()).getBytes());
Thread.sleep(5000);
System.out.println("结束与客户端交互数据");
os.close();
client.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}.start();
}
}
}
public class Main{
public static void main(String[] args)throws Exception
{
new TCPSever().listen();
}
}
//第二个项目
package com.itheima;
import java.net.*;
import java.io.*;
import java.util.Scanner;
class TCPClient{
private static final int PORT = 7788;
static Scanner in = new Scanner(System.in);
public void connect()throws Exception{
Socket client = new Socket(InetAddress.getLocalHost(), PORT);
InputStream is = client.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
//传出字符串
OutputStream ot = client.getOutputStream();
String str = in.next();
ot.write((str).getBytes());
//传入字符串
byte[] buff = new byte[1024];
int len1 = is.read(buff);
String st = new String(buff, 0, len1);
System.out.println(st);
client.close();
}
}
public class Main{
public static void main(String[] args)throws Exception{
new TCPClient().connect();
}
}
//第一个项目package com.itheima;import java.net.*;import java.io.*;class TCPSever{ private static final int PORT = 7788; public static void listen()throws Exception{ ServerSocket serverSocket = new ServerSocket(PORT); while(true).