服务器端importjava.net.*;importjava.io.*;publicclasstestServer{publicstaticvoidmain(String[]args){try{ServerSockets=newServerSocket(5050);Socketss=s.accept();InputStreami...
服务器端
import java.net.*;
import java.io.*;
public class testServer {
public static void main(String[] args){
try{
ServerSocket s=new ServerSocket(5050);
Socket ss=s.accept();
InputStream is=ss.getInputStream();
DataInputStream dis=new DataInputStream(is);
OutputStream os=ss.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
new ServerReader(dis).start();
new ServerWriter(dos).start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class ServerReader extends Thread{
private DataInputStream dis;
public ServerReader(DataInputStream dis){
this.dis=dis;
}
public void run(){
String input;
try{
while(true){
input=dis.readUTF();
System.out.println("Client:" +input);
if(input.equals("bye"))
{
System.out.println("Other quit...");
System.exit(0);
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class ServerWriter extends Thread{
private DataOutputStream dos;
public ServerWriter(DataOutputStream dos){
this.dos=dos;
}
public void run(){
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String input;
try{
while(true){
input=br.readLine();
dos.writeUTF(input);
if(input.equals("bye")){
System.out.println("quit...");
System.exit(0);
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
客户端
package example;
import java.io.*;
import java.net.Socket;
public class testClient {
public static void main(String[] args){
try{
Socket ss=new Socket("192.168.1.120",5050);
InputStream is=ss.getInputStream();
DataInputStream dis=new DataInputStream(is);
OutputStream os=ss.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
new ClientReader(dis).start();
new ClientWriter(dos).start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class ClientReader extends Thread{
private DataInputStream dis;
public ClientReader(DataInputStream dis){
this.dis=dis;
}
public void run(){
String input;
try{
while(true){
input=dis.readUTF();
System.out.println("Server: "+input);
if(input.equals("bye")){
System.out.println("Other quit...");
System.exit(0);
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class ClientWriter extends Thread{
private DataOutputStream dos;
public ClientWriter(DataOutputStream dos){
this.dos=dos;
}
public void run(){
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String input;
try{
while(true){
input=br.readLine();
dos.writeUTF(input);
if(input.equals("bye")){
System.out.println("quit...");
System.exit(0);
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
我要代码。。。。直接添加到我的代码里,或修改,不要全改。。。
展开