package FromScreen;
import java.io.Serializable;
import java.util.Scanner;
public class FromScreen implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3552585161044065350L;
private Scanner sc = new Scanner(System.in);
public String getStringFromScreen() //从控制台得到用户输入数据
{
return sc.nextLine();
}
}
客户端:
package FromScreen;
import java.io.*;
import java.net.*;
public class tcpClient {
public static void main(String[] args) throws IOException{
Socket ss=new Socket("127.0.0.1",8888);
System.out.println("Socket:"+ss);
try{
//套接字建立成功,建立I/O流进行通信
DataInputStream dis=new DataInputStream(ss.getInputStream());
DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
FromScreen fs=new FromScreen();
for(int i=0;i<=100;i++)
{
dos.writeUTF("tcoClient "+fs.getStringFromScreen());
dos.flush();
//if(fs.getStringFromScreen().equals("end")) break;
System.out.println(dis.readUTF());
}
dos.writeUTF("end");
dos.flush();
dos.close();
dis.close();
}finally{
ss.close();
}
}
}
服务器端:
package FromScreen;
import java.io.*;
import java.net.*;
public class tcpServer {
public static final int PORT=8888;
public static void main(String[] args) throws IOException{
//建立ServerSocket
ServerSocket s=new ServerSocket(PORT);
System.out.println("ServerSocket:"+s);
try{
Socket ss=s.accept();
System.out.println("Socket accept:"+ss);
FromScreen fs=new FromScreen();
try
{
DataInputStream dis=new DataInputStream(ss.getInputStream());
DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
//在循环中,与客户机通信
while(true)
{
String str=dis.readUTF(); //从客户机中读数据
if(str.equals("end"))break; //当读到end时,程序终止
System.out.println(str);
dos.writeUTF("tcpServer :"+fs.getStringFromScreen()); //向客户机中写数据
}
dos.close();
dis.close();
}finally{
ss.close();
}
}finally{
s.close();
}
}
}
Tcp这个地方感觉与UDP好像啊,有点复杂 |
|